Custom Matchers for Jest
Learn what a matcher is, why we need them, and how to develop your own.
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:
Press + to interact
expect(1).toBe(1); // Checking for value and reference equalityexpect({a: 'b'}).toEqual({a: 'b'}); //Checking for deep value equalityexpect('abacaba').toMatch(/bac/); // Checking if a string matches a regexpexpect({a: 'b', b: 'c'}).toMatchObject({a: 'b'}); // Checking for a partial object matchexpect([1, 2, 3]).toContainEqual(2); // Checking if an array contains an elementexpect(2).not.toEqual(3); // using not to negate any matcherexpect({a: 'b'}).toMatchObject({a: expect.any(String)}); // Type checkingconst mockFunction = jest.fn(); // Creating a mock functionexpect(mockFunction).toHaveBeenCalled(); // Checking if it was calledexpect(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 ...
Access this course and 1400+ top-rated courses and projects.