Matchers
Use Jest matchers for equality, types, exceptions, async results, and custom assertions.
Basic Matchers
toBe checks strict equality for primitives. toEqual recursively compares object structure. toStrictEqual additionally fails on undefined vs missing key differences.
Use toMatch for strings against regex or substring. toContain works for arrays and strings.
expect("hello world").toMatch(/world/);
expect([1, 2, 3]).toContain(2);
expect(["a", "b"]).toEqual(expect.arrayContaining(["a"]));Type and Truthiness Matchers
toBeNull, toBeUndefined, toBeDefined, and toBeTruthy/toBeFalsy express presence and truthiness checks. Prefer explicit matchers over generic truthy checks for clearer failure messages.
Number matchers include toBeGreaterThan, toBeCloseTo for floating point, and toNaN for NaN checks.
- Avoid toBeTruthy on objects—empty {} is truthy
- Use not.toBe for negation of any matcher
- expect.any(Constructor) matches instance types loosely
expect(value).toBeDefined(); expect(count).toBeGreaterThan(0); expect(0.1 + 0.2).toBeCloseTo(0.3);
Exception Matchers
toThrow verifies synchronous functions throw. Pass error class or message regex for specificity. For async functions, use rejects.toThrow after returning the promise to expect.
Combine with expect.hasAssertions() in error-path tests to ensure throw branches execute.
expect(() => divide(1, 0)).toThrow("Division by zero");
await expect(fetchUser("missing")).rejects.toThrow(NotFoundError);Object and Array Matchers
expect.objectContaining and expect.arrayContaining perform partial matching. toHaveProperty checks nested keys with optional value. toMatchObject compares subset of object fields.
Asymmetric matchers compose inside toEqual for flexible structural assertions without brittle full-object equality.
expect(response).toEqual(
expect.objectContaining({
status: 200,
body: expect.objectContaining({ id: expect.any(String) }),
})
);Custom Matchers
Extend Jest with expect.extend in setupFilesAfterEnv for domain-specific assertions—valid UUID format, API response shape, or accessibility rules.
Custom matchers return { pass, message } objects. Register TypeScript types for autocomplete on custom matcher names.
expect.extend({
toBeValidEmail(received: string) {
const pass = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(received);
return {
pass,
message: () => `expected ${received} to be a valid email`,
};
},
});