Skip to the page

Test runners, assertions and mocks · core

Test anatomy, assertions and async tests

A good test arranges data, acts once and asserts the result; toBe compares with Object.is, toEqual compares structure recursively (ignoring undefined properties), toStrictEqual also checks undefined properties and classes, and an async test must await or return its promise or it can pass while the check fails later.

The notes

What you must know

  • Structure: describe for grouping, test/it for one behaviour, beforeEach for shared setup. Arrange, Act, Assert.
  • toBe(x) uses Object.is: same primitive value or the same object reference. Object.is(NaN, NaN) is true; Object.is(0, -0) is false.
  • toEqual compares values recursively and ignores properties that are undefined; toStrictEqual also fails on undefined properties, sparse arrays and different classes.
  • toThrow needs a function: expect(() => parse('x')).toThrow(), not expect(parse('x')).toThrow().
  • Async: await the promise (or return it); use await expect(p).rejects.toThrow(). A promise you don't await may fail after the test has already passed.
  • expect.assertions(n) or expect.hasAssertions() guards against callbacks that never run.

The red pen

Common traps: mistake → fix

  • Mistake: "toBe works for objects with the same content"

    Fix: toBe checks reference; use toEqual for content.

  • Mistake: "A test without await still checks the async result"

    Fix: the test function returns before the promise settles, so it passes.

  • Mistake: "toEqual and toStrictEqual are the same"

    Fix: toEqual ignores undefined properties and class types.

Easy to hard

Questions interviewers ask, easy to hard

  1. toBe vs toEqual vs toStrictEqual?
  2. How do you test that an async function rejects?
  3. Why did this async test pass even though the code is broken?
  4. Write a tiny test runner with test() and expect().toBe().

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview