This posts will show how you can keep your test code clean by using a builder to generate your test data.
Imagine we have an model Movie where we store:
We need to test & implement a Movie Service where we expose 2 functions:
In the getTitlesByGenre() function, only the genre and title attributes are relevant. In the getTitlesByDirector() function, only the title and director are important.
While I prefer to work with full blown movie objects in my tests, I only want to specify the values of the attributes that really matter to my test. This is something I typically solve by creating a movieBuilder
Generating Test Data
This module provides 2 functions to create complete or partial randomized movie objects:
movie() creates a movie object where all its attributes are randomized. It uses chance to generate realistic random data.
movieWith() creates a movie object with all its attributes randomized, except for those specified in the override argument.
An example of invoking movie()
And an example of invoking movieWith(override)
Let’s see now how we can benefit from this in our tests:
The movieWith() function allows us to specify only the data relevant to the functionality we’re implementing.
All other data is randomized. It keeps the test code clean and readable.
For completeness, here is a possible implementation (and the package.json file):