Search code examples
javascriptmocha.jstddchai

When to stop when trying to write meaningful tests using TDD?


I'm struggling to find when to stop writting test cases using TDD.

Let's say a have to write a method that only accepts some strings, it can only accept the strings ['red', 'green', 'blue'], it is required and can't be empty.

I write the first failing test, make it green, and so on and so forth until I have the test cases:

it('should accept red input', () => { /*...*/ }
it('should accept green input', () => { /*...*/ }
it('should accept blue input', () => { /*...*/ }
it('should not accept null input', () => { /*...*/ }
it('should not accept empty input', () => { /*...*/ }

At this point everything is passing, now should I call it a day and go or should I go and add a test if it fails for Purple? Is it meaningful to add this test? If it is, I still can name other 10 colours to test, should I consider them all too?

This example is simple, but there are cases with Regexes that have infinite combinations that I know that could be a problem and I can't add all test cases I can think of for time constraints. These are worst, because I don't know when to stop writing test code, and find when enough is enough.

I undertand I can't get a concrete anwser for this, but I would like to hear from experience what works most of the time.


Solution

  • Generally you want to test for input classes instead of specific inputs, unless you know already that a specific input will produce a specific situation you need to cover with the tests.

    In your example I would break it down to four tests:

    1. Should accept a color in expected input space, e.g. 'red'
    2. Should not accept a color not in expected input space, e.g. 'purple'
    3. Should not accept an empty input
    4. Should not accept a null input

    You're right that with parsing the input space is huge and covers more cases than you can realistically test. In that case I'd go for some common cases (the null/empty inputs, the clearly expected and unexpected inputs, etc.) and try to think of specific scenarios where an input might be miss-classified as (un-)expected. Maybe there are two colors 'red' and 'reddish' and you want to test that the function covers both or one, but not the other. The specific colors are not important in this case, just that one contains the other.