A quick reference for commonly used jest matchers. A full list can be found on their docs page
toBe
- For exact match (Not for different objects or arrays)
- Uses
Object.is
for equality check
toEqual
- For exact match of arrays and objects
- Recursively checks every field of an object or array.
- Ignores
undefined
or empty values
toStrictEqual
- For additionally checking the equality of data types as well
- For example, checking the difference between instance of
User class
and an user object literal having same props as the instance. .toEqual
will pass it as same objects but nto.toStrictEqual
NOTE: A great article explaining detailed difference between
toEqual
andtoStrictEqual
not
- Opposite of matcher
- To test something like
.not.toBe()
Truthiness
toBeNull
matches onlynull
toBeUndefined
matches onlyundefined
toBeDefined
is the opposite oftoBeUndefined
toBeTruthy
matches anything that an if statement treats astrue
toBeFalsy
matches anything that an if statement treats asfalse
Numbers
toBeGreaterThan
toBeGreaterThanOrEqual
toBeLessThan
toBeLessThanOrEqual
toBe
andtoEqual
are equivalent for numberstoBeCloseTo
for floating points. Can be used to avoid small rounding errors while testing.
Strings
toMatch
for checking strings against regular expressions.
Arrays and iterables
toContain
to check if an item exist in an array or iterable (Example a Set)
Exceptions
toThrow
to test thrown errors by functions- It accepts an
Error
,string
orregular expression
to compare the thrown Error or message.
TIP: For more Jest matchers, check out jest-extended