Using Common Matchers

Learn about matchers, the tool at the center of Jest's testing ease.

What are matchers?

A matcher is what facilitates the assertion portion of a test. It states what we are asserting to be true, ultimately determining the passing or failing of the test.

Jest’s expect function provides a number of these as an out-of-the-box feature. All these are called by simply chaining them onto expect, as shown below:

expect(2 + 2).toEqual(4);

Types of matchers

The matcher library is robust, offering lots of flexibility. Most matchers fall into one of the following categories:

  • Truthiness
  • Equality
  • Numerical comparison
  • Exceptions
  • Function calls

Common matchers

.toBe(): This checks the equality of two primitive values but can’t reliably be used with floating point numbers. Keep in mind that these primitive values can be booleans. Therefore, we can pass our expect function something that equates to a boolean and then use .toBe(true) or .toBe(false).

To compare two objects, we can either use the referential identity to compare a key-value pair from each object, or we can use Object.is for comparison:

expect(Object.is(obj1, obj2)).toBe(true)

This matcher is very flexible, but many of these needs are abstracted into other more explicit matches.

.toMatch(): It allows us to leverage regex patterns for testing strings. Sometimes, we have dynamic text that we particularly want to ensure is rendering properly. This is an easy and clear way to do this without getting bogged down in the context.

.toBeTruthy() + .toBeFalsy(): These are pretty self-explanatory and are great examples of the explicit abstractions of the .toBe() testing. It is straightforward and easily readable.

.toHaveBeenCalled(): It tells us if a mock function has been called. It doesn’t tell us anything about what the function does, just whether or not it was called. It’s incredibly useful when, for instance, we have a low-level button component that can do anything we tell it to—we just need to make sure that clicking it will in fact perform the desired task.

Remember that we can only check if a mock function has been called.

.toBeNull(): This asserts that the expected value is equal to null.

.toContain(): It checks whether or not an item is present in an array. The array should be passed to expect, and the item passed to toContain().

.not: This lets us test the opposite of any matcher available. It would be equivalent to making an assertion using the ! operator, but it’s much more readable.

Get hands-on with 1200+ tech skills courses.