Improve your Javascript unit testing with Parameterized tests

Ninja JavaScript
2 min readMar 19, 2017

--

Parameterized tests allow a developer to run the same test over and over again using different values. This can be useful if you need to test that your function can handle a range of different inputs, including edge cases. It can be impractical to write an individual test for each input.

Mocha unit tests

In this contrived example, we want to test our validateName function with a a range of different inputs to try and break it. Here we are using three, but what if we want to test with hundreds? We want to avoid duplicating the same test again and again.

Parameterized tests

Many testing frameworks such as JUnit, NUnit and MSTest offer parameterized testing as a feature and have done so for years. Unfortunately for us Javascript developers, Mocha does not support this feature out of the box. People generally seem to work around the problem by writing their own forEach loops and iteratively calling their unit tests. Though this works, it can lead to a slightly confusing, cluttered syntax which can detract from the precise purpose of the test.

Moch param

There is a npm package, mocha-param, that can provide a clean syntax for adding Parameterized tests to mocha. This is the example above re-written:

data in this example is just a list of invalid names. We can add as many as we like and we completely avoid duplication.

If you write Parameterized tests differently, or have any thoughts/reactions please let me know in the comments below.

--

--