DEV Community

Discussion on: Why practicing DRY in tests is bad for you

Collapse
 
jakecarpenter profile image
Jake Carpenter • Edited

I agree your example of test theories is an example of a bad test, but only because of the way it is communicated by the test. Test theories are not inherently bad or an example of being DRY, but they do require careful communication of what you're testing because it's easy to lump different scenarios under the same set of cases.

The best way to do this is to utilize the BDD-nature of Jest. This is still a contrived example, but if you're not using CTRL+Click from the terminal to jump to your failing test then it still gives you a better description:

describe('Add function', () => {
  describe('should add two positive numbers correctly', () => {
    const theories = [
      [1, 1, 2],
      [21, 33, 54],
      [100, 88, 188],
    ]

    test.each(theories)('given %i and %i then %i', (a, b, expected) => {
      expect(add(a, b)).toBe(expected)
    })
  })
})
Enter fullscreen mode Exit fullscreen mode

I feel a lot of people dislike "nesting" tests and descriptions this way, but it's really one of the intended strengths. I was taught testing in Javascript by one of the maintainers of Jasmine who used BDD patterns very effectively.

Personally I dislike the naming templates with jest.each() and use jest-theories in my own current projects.

None of this is arguing against your broader point of being too DRY in tests though. I very much agree with that and feel the most common mistakes involve shared test setup.