Jest · Unit tests that survive refactors

How do expect and matchers work in Jest?

EasymatchersassertionsexpectUpdated Oct 2026
Quiz this track

Short answer

expect(value) returns an object of matchers. Use toBe for primitives or identity, toEqual for deep structural equality, and the most specific matcher available for clearer failures.

A matcher is a function that compares the received value with an expected one and throws a descriptive error when the comparison fails. Choosing a precise matcher produces a better failure message than wrapping everything in a boolean check.

ts
const user = { id: 1, name: "Asha", roles: ["admin"] };

expect(2 + 2).toBe(4);
expect(user).toEqual({ id: 1, name: "Asha", roles: ["admin"] });
expect(user).toMatchObject({ name: "Asha" });
expect(user.roles).toContain("admin");
expect("asha@example.com").toMatch(/@example\.com$/);
expect(user.name).toHaveLength(4);
expect(null).toBeNull();
expect(undefined).toBeUndefined();

Matcher families

  • Equality: toBe for identity, toEqual for deep equality, toStrictEqual to also check types and undefined keys
  • Structure: toMatchObject, toHaveProperty, toContain, toHaveLength
  • Truthiness and nullability: toBeTruthy, toBeFalsy, toBeNull, toBeDefined
  • Numbers: toBeGreaterThan, toBeCloseTo and domain matchers
  • Errors and mocks: toThrow, toHaveBeenCalledWith, toHaveBeenCalledTimes

toBe uses Object.is, so two structurally identical objects fail because they are different references. toEqual ignores undefined properties and does not check class identity, while toStrictEqual is stricter. For a value that should be exactly a plain object, toStrictEqual catches accidental extra keys.

Avoid expect(value).toBe(true) when a purpose-built matcher exists. toBeNull, toContain and toHaveBeenCalledWith explain intent and report the actual value on failure.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between toBe and toEqual?
  2. 2When would toStrictEqual catch a bug that toEqual misses?
  3. 3How do you assert on floating-point numbers?
  4. 4Why is a vague boolean assertion a problem?

Say it in the interview

expect wraps a value and gives me matchers. I use toBe for primitives and reference identity, toEqual for structural equality, and toStrictEqual when extra or undefined keys should fail. I pick the most specific matcher, such as toContain or toMatchObject, because the failure output is easier to read. I avoid collapsing everything into a true or false assertion.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.