Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the
expect API doc.
The simplest way to test a value is with exact equality.
In this code,
expect(2 + 2) returns an "expectation" object. You typically won't do much with these expectation objects except call matchers on them. In this code,
.toBe(4) is the matcher. When Jest runs, it tracks all the failing matchers so that it can print out nice error messages for you.
Object.is to test exact equality. If you want to check the value of an object, use
toEqual recursively checks every field of an object or array.
You can also test for the opposite of a matcher:
In tests, you sometimes need to distinguish between
false, but you sometimes do not want to treat these differently. Jest contains helpers that let you be explicit about what you want.
toBeDefinedis the opposite of
toBeTruthymatches anything that an
ifstatement treats as true
toBeFalsymatches anything that an
ifstatement treats as false
You should use the matcher that most precisely corresponds to what you want your code to be doing.
Most ways of comparing numbers have matcher equivalents.
For floating point equality, use
toBeCloseTo instead of
toEqual, because you don't want a test to depend on a tiny rounding error.
You can check strings against regular expressions with
You can check if an array or iterable contains a particular item using
If you want to test whether a particular function throws an error when it's called, use
Note: the function that throws an exception needs to be invoked within a wrapping function otherwise the
toThrowassertion will fail.
This is just a taste. For a complete list of matchers, check out the reference docs.
Once you've learned about the matchers that are available, a good next step is to check out how Jest lets you test asynchronous code.