Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Is DRY coding important when testing?

const expect = require('chai').expect;

describe('checkForShip',() => {
  const checkForShip = require('../game_logic/ship_methods').checkForShip;
  const player = {
    ships: [
      {
        locations: [[0,0],[0,1]]
      }
    ]
  }
  it('should correctly report no ship at a given players coordinate', () => {
    expect(checkForShip(player, [9,9])).to.be.false;
  });
  it('should correctly report a ship located at the given coordinate', () => {
    expect(checkForShip(player, [0,0])).to.be.true;
  });
  it('should handle ships located at more than one coordinate', () => {
    expect(checkForShip(player, [0,0])).to.be.true;
    expect(checkForShip(player, [0,1])).to.be.true;
    expect(checkForShip(player, [9,9])).to.be.false;
  });
  it('should handle multiple ships', () => {
    expect(checkForShip(player, [0,0])).to.be.true;
    expect(checkForShip(player, [0,1])).to.be.true;
    expect(checkForShip(player, [9,9])).to.be.false;
  });
});

I feel a dry approach always makes the code more readable but in the case of unit testing would DRYer code make the spec lose value in it's behavior description?

In the video, Guil would show that he wrote a new 'player' and 'checkForShip' in each 'it' statement, and would customize the player to illustrate a new situation per spec. So I was wondering if losing that extra behavior description was at all worth writing more DRY code.

1 Answer

Dane Parchment
MOD
Dane Parchment
Treehouse Moderator 11,077 Points

Ironically the opposite is actually true for Unit Tests!

The term DAMP not DRY is quite popular in the testing community, because when it comes to testing code you want to be as descriptive as possible.

DAMP means: Descriptive and Meaningful Phrases, and it does pretty much what it says on the tin. Unit tests are going to be inherently duplicated, so make sure they are as descriptive as possible.

Here is a link to a really good answer as to why you should be following DAMP over DRY code in Unit Testing: https://stackoverflow.com/questions/6453235/what-does-damp-not-dry-mean-when-talking-about-unit-tests


Also on a side note, your last two unit tests are testing the exact same thing, so the last test is kinda pointless.