Search⌘ K
AI Features

Custom Matchers for Jest

Explore how to create and implement custom matchers in Jest to improve the readability and efficiency of your tests. Understand writing matchers that accept arguments and setting up your Jest environment for tailored assertion functions.

What is a matcher?

A matcher (or an assertion) is a function that is used to check for a specific condition. Most often, it compares two values. Here are some of the basic matches available in Jest:

JavaScript (JSX)
expect(1).toBe(1); // Checking for value and reference equality
expect({a: 'b'}).toEqual({a: 'b'}); //Checking for deep value equality
expect('abacaba').toMatch(/bac/); // Checking if a string matches a regexp
expect({a: 'b', b: 'c'}).toMatchObject({a: 'b'}); // Checking for a partial object match
expect([1, 2, 3]).toContainEqual(2); // Checking if an array contains an element
expect(2).not.toEqual(3); // using not to negate any matcher
expect({a: 'b'}).toMatchObject({
a: expect.any(String)
}); // Type checking
const mockFunction = jest.fn(); // Creating a mock function
expect(mockFunction).toHaveBeenCalled(); // Checking if it was called
expect(mockFunction).toHaveBeenCalledWith('abacaba'); // Checking for arguments

Why do we need custom matchers?

While Jest is very powerful out-of-box, there is always something specific to the project that you can add. It should improve readability and reduce the amount of code by creating a custom Jest matcher for a common use case.

In one of my projects, I had to test whether a certain value was a correctly formatted ISO date. It can be done with a regular expression, but I had to test it so many times, it was worth moving this logic to a custom Jest matcher.

Add a setup file

Before we add the matcher itself, it is important to add a setup file for Jest. A setup file is a file that is ...