Using Matchers
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.
#
Common MatchersThe 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.
toBe
uses Object.is
to test exact equality. If you want to check the value of an object, use toEqual
instead:
toEqual
recursively checks every field of an object or array.
You can also test for the opposite of a matcher:
#
TruthinessIn tests, you sometimes need to distinguish between undefined
, null
, and false
, but you sometimes do not want to treat these differently. Jest contains helpers that let you be explicit about what you want.
toBeNull
matches onlynull
toBeUndefined
matches onlyundefined
toBeDefined
is the opposite oftoBeUndefined
toBeTruthy
matches anything that anif
statement treats as truetoBeFalsy
matches anything that anif
statement treats as false
For example:
You should use the matcher that most precisely corresponds to what you want your code to be doing.
#
NumbersMost 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.
#
StringsYou can check strings against regular expressions with toMatch
:
#
Arrays and iterablesYou can check if an array or iterable contains a particular item using toContain
:
#
ExceptionsIf you want to test whether a particular function throws an error when it's called, use toThrow
.
Note: the function that throws an exception needs to be invoked within a wrapping function otherwise the
toThrow
assertion will fail.
#
And MoreThis 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.