• Skip to primary navigation
  • Skip to main content

Test-first

Master the art of Test-driven Development (TDD)

  • Home
  • Newsletter
  • Blog

Test Anti-pattern: Not using the best available matcher

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:

❌ avoid:

expect(circumference).toBe(Math.round(PI * 2 * 2 * 10000) / 10000)

âś… prefer:

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:

❌ avoid:

expect(items.length).toBe(3)

âś… prefer:

expect(items).toHaveLength(3)

The difference between the two examples above is the output in case of a bug.

If 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.

With .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 .toBePositive() or 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,
-David

Get David’s best advice on TDD straight to your inbox

Tap into a senior software developer’s brain with 25 years of industry-relevant experience that successfully uses Test-driven Development daily.

I’ll send you a few emails per month to keep you posted. Of course, you can opt out at any time.
By subscribing, you accept my privacy policy. I promise I won’t spam you or sell your data.

Connect

  • Email
  • LinkedIn
  • Phone
  • YouTube

Discover

www.cultivate.software

Legal

Imprint  ·  Privacy Policy  ·  Cookie Policy

Copyright © 2025 · cultivate GmbH