Here’s another common test anti-pattern that makes working with tests harder than it needs to be.
🛑 Test Anti-pattern 🛑
Not using the best available matcher
Matchers are little helper functions that let you verify test conditions more elegantly.
Most testing frameworks like Jest come with a predefined set of matchers (a.k.a. assertions). For instance:
expect(sum).toBe(42) expect(skills).toContain('TDD'); expect(temperature).toBeLessThan(100)
Not using the best available matcher can significantly decrease the readability — and waste precious development time:
expect(circumference).toBe(Math.round(PI * 2 * 2 * 10000) / 10000)
expect(circumference).toBeCloseTo(PI * 2 * 2, 4)
Besides improved readability and time savings, there’s another benefit. Using the best possible matcher will also improve the error message presented to you when a test fails:
The difference between the two examples above is the output in case of a bug.
items is unexpectedly
undefined, the example to avoid will result in the following error message:
TypeError: Cannot read properties of undefined (reading 'length')
This error message could be more helpful, and a developer might lose precious development time while trying to figure out what’s happening.
.toHaveLength(..), however, we would get an improved error message:
expect(received).toHaveLength(expected) Matcher error: received value must have a length property whose value must be a number Received has value: undefined
By the way, you don’t have to limit yourself to the predefined matchers, either. Jest Extended is an excellent library of additional matchers like
toEndWith(..) that shouldn’t be missing in any project.
Here are again the three benefits of using the correct matcher:
- test code is easier to read
- less test code to write
- error messages are more helpful
Each of the above points represents a reduction of development time and thus costs.
So, always use the best matcher available!
See you around,