Code Reference

Matchers

Jest · Reference cheat sheet

Matchers

Jest · Reference cheat sheet


📋 Overview

expect(value) matchers assert equality, truthiness, numbers, strings, collections, and errors. Prefer asymmetric matchers for partial object checks.

🔧 Core concepts

MatcherUse
toBeReferential / primitives (Object.is)
toEqualDeep equality
toStrictEqualDeep + undefined keys
toMatch / toContainString / array
toThrowSync exceptions
toBeCloseToFloats
toHaveBeenCalledMocks

Chain .not, .resolves, .rejects.

💡 Examples

Equality:

expect(1 + 1).toBe(2);
expect({ a: 1 }).toEqual({ a: 1 });
expect({ a: 1 }).toStrictEqual({ a: 1 });

Truthiness & numbers:

expect(x).toBeTruthy();
expect(x).toBeNull();
expect(x).toBeUndefined();
expect(0.1 + 0.2).toBeCloseTo(0.3);
expect(score).toBeGreaterThan(10);

Collections & strings:

expect(['a', 'b']).toContain('a');
expect('hello').toMatch(/ell/);
expect({ a: 1, b: 2 }).toMatchObject({ a: 1 });
expect([{ id: 1 }]).toContainEqual({ id: 1 });

Asymmetric:

expect(user).toEqual({
  id: expect.any(Number),
  email: expect.stringMatching(/@/),
  meta: expect.objectContaining({ role: 'admin' }),
});

Errors:

expect(() => parse('')).toThrow(Error);
expect(() => parse('')).toThrow(/empty/);

⚠️ Pitfalls

  • toBe on objects compares references — use toEqual.
  • Floating point with toBe — use toBeCloseTo.
  • toThrow needs a wrapped function, not a thrown call.
  • Over-specific snapshots instead of focused matchers.
  • Forgetting await expect(...).resolves for promises.

On this page