Creating Matchers to Simplify Tests
This chapter introduces another method for simplifying tests: building custom matchers. Most of the time, it makes sense to stick to the built-in matchers. For instance, the powerful combination of the toEqual
matcher with the expect.objectContaining
and expect.arrayContaining
functions make it easy to build expressive expectations.
But sometimes it makes sense to build a matcher that can scoop up a number of different checks into one single check. This not only shortens tests but can make them more readable, too.
In Chapter 5, Validating Form Data, each of the form validation rules was tested by a describe
context with four tests, like this:
describe('when the date of birth is in the wrong format') it('does not save the birthday', ...) it('returns a 422', ...) it('returns a useful message', ...) it('returns the other data back including the incorrect...