Javascript – How to write good javascript unit test descriptions

javascriptunit testing

I come from a python background. I typically write long unit test descriptions that link the test to a user story. The test is as much about justifying why the code exists and how it fits into the larger system as it is about testing for correctness. As such my tests often have about as much docstring text as test code.

In javascript it's more typical to use the describe and it syntax. Something like Describe makeFoo – it should return a foo. I don't see many long descriptions. This works fine for TDD but I get less sure on where to document why the code exists in the first place. Why does makeFoo return foo seems more important me than if it does in fact return a foo.

Does anyone have advice or examples for what makes a good javascript test description? Should I just move my user stories outside the test? Write them only on integration tests? Add really long describe strings? Or am I missing some greater point about this style of testing?

Best Answer

Note that if you're perfectly happy with the style of descriptions you used to write in Python, there is no reason to change that. Put the name of the tested block within the describe, and put your description in it. If it's clear for you, it doesn't matter what the designers of the test framework had in mind.

If you're for some reason unhappy with porting your style to JavaScript, then stick with it('should do this or that'), and just below it, include the complete description:

describe('the ruler', () => {
    describe('after a double-click', () => {
        it('should reflect the cursor position instead of assuming a (0, 0)', () => {
            /**
             * The edge case documented in CAP-621 happens when a user, instead of simply
             * clicking once to position the first side of the ruler, and then click
             * another time somewhere else to fix the ruler on the page, double-clicks on
             * the page. The previous behavior was that the ruler was drawn from the cursor
             * to the (0, 0) of the page. Instead, a double-click should be treated as if
             * it was a simple click, letting the user to position the other side of the
             * ruler with another click or double-click.
             */
            ...
        });
    });
});

When reading a test, for instance in the context where a change in the code broke it, either you'll understand its purpose just by looking at its name, or you'll read the long comment. This style may even be preferable to having only the long description: if the test is recent or if it concerns a part you were working on recently, chances are, you won't need the whole description, and having a short name would save you time.

Related Topic