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.isfor equality check
toEqual
- For exact match of arrays and objects
- Recursively checks every field of an object or array.
- Ignores
undefinedor empty values
toStrictEqual
- For additionally checking the equality of data types as well
-
For example, checking the difference between instance of
User classand an user object literal having same props as the instance. .toEqualwill pass it as same objects but nto.toStrictEqual
NOTE: A great article explaining detailed difference between
toEqualandtoStrictEqual
not
- Opposite of matcher
- To test something like
.not.toBe()
Truthiness
toBeNullmatches onlynulltoBeUndefinedmatches onlyundefinedtoBeDefinedis the opposite oftoBeUndefined-
toBeTruthymatches anything that an if statement treats astrue -
toBeFalsymatches anything that an if statement treats asfalse
Numbers
toBeGreaterThantoBeGreaterThanOrEqualtoBeLessThantoBeLessThanOrEqual-
toBeandtoEqualare equivalent for numbers -
toBeCloseTofor floating points. Can be used to avoid small rounding errors while testing.
Strings
toMatchfor checking strings against regular expressions.
Arrays and iterables
-
toContainto check if an item exist in an array or iterable (Example a Set)
Exceptions
toThrowto test thrown errors by functions-
It accepts an
Error,stringorregular expressionto compare the thrown Error or message.
TIP: For more Jest matchers, check out jest-extended