Look up Jest matchers without leaving your editor mindset
Jest’s expect() exposes many matchers, and remembering which to use for
references, structure, numbers, exceptions, mocks and promises is half the
battle. This reference lists every common matcher, what it asserts, the
argument it takes and whether it has an async form, plus the .not,
.resolves and .rejects modifiers. It runs entirely in your browser.
How it works
An assertion is expect(value).matcher(expected). The matcher decides the
comparison: toBe is Object.is reference equality, toEqual is recursive
structural equality, toContain checks membership, and toThrow runs a wrapped
function and inspects the error. Modifiers chain before the matcher: .not
inverts it, and .resolves/.rejects unwrap a promise:
expect(2 + 2).toBe(4);
expect([1, 2]).toEqual([1, 2]);
expect(() => parse("")).toThrow(/empty/);
await expect(fetchUser(1)).resolves.toHaveProperty("id", 1);
expect(mockFn).toHaveBeenCalledWith("ready");
Tips and examples
- Prefer
toStrictEqualovertoEqualwhen you also want to catchundefinedproperties and mismatched class types. - Use
expect.assertions(n)at the top of async tests to guarantee a callback assertion actually ran. toMatchObjectchecks that an object contains a subset of expected properties, ignoring extras — handy for API responses.- Snapshot matchers
toMatchSnapshotandtoMatchInlineSnapshotstore the rendered value on first run and compare on later runs.