skip to content

Test Structure and Matchers

Structuring specs with describe and it, and asserting with expect — toBe versus toEqual, toThrow, toMatchObject, asymmetric and custom matchers. A rapid-fire question, and toBe versus toEqual catches people out constantly.

on this pageshow

explore

questions

6

In a Jest 30 test, how do toBe, toEqual and toStrictEqual differ when the value under test is an object or an array?

level: juniorimportance: must knowfreq 85%

answer

  1. identity versus structure
  2. Object.is, not ===
  3. what toEqual quietly forgives
  4. class type and undefined keys

basics

~10 s

toBe checks identity with Object.is, so two separately built objects never match. toEqual compares recursively but ignores undefined-valued keys, array sparseness and class type; toStrictEqual compares recursively and checks all three.

solid answer

~40 s

`toBe` calls `Object.is`, so for an object or array it asks whether both sides are the *same reference*: two literals with identical fields fail, and the failure output suggests switching to a deep-equality matcher. `toEqual` walks both values recursively and compares primitives with `Object.is`, but it is lenient: a key whose value is `undefined` counts as absent, `[, 1]` equals `[undefined, 1]`, a class instance equals a plain object with the same fields, and two `Error` objects match on `message` alone. `toStrictEqual` does the same walk without those allowances. So use `toBe` for primitives and deliberate identity checks, `toStrictEqual` when the exact shape is the contract (a payload you serialize, a value another layer compares), and `toEqual` when you mean *same data, whatever the class*.

code

javascript · 23 lines
javascript
class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  }
}

function quoteTotal(items) {
  const amount = items.reduce((sum, item) => sum + item.price, 0);
  return { total: new Money(amount, 'EUR'), discount: undefined };
}

test('quoteTotal builds a fresh result object', () => {
  const items = [{ price: 0.1 }, { price: 0.2 }];
  const quote = quoteTotal(items);

  expect(quote).not.toBe(quoteTotal(items)); // two calls, two objects
  expect(quote.total.amount).toBeCloseTo(0.3); // 0.30000000000000004
  expect(quote.total).toEqual({ amount: quote.total.amount, currency: 'EUR' }); // class ignored
  expect(quote.total).not.toStrictEqual({ amount: quote.total.amount, currency: 'EUR' }); // class checked
  expect(quote).toEqual({ total: quote.total }); // undefined key ignored
  expect(quote).not.toStrictEqual({ total: quote.total }); // undefined key checked
});

go deeper

for a junior

Recall that toBe is Object.is identity, so freshly built objects need toEqual or toStrictEqual, and that floating-point results need toBeCloseTo.

for a middle

Explain exactly what toEqual forgives: undefined-valued keys, sparse arrays, class type and error fields beyond the message, and show a case where toStrictEqual catches a real bug.

for a senior

Choose the matcher by what consumes the value: serialized payloads and exact shapes deserve toStrictEqual, because a toEqual pass can hide an undefined field leaking downstream.

for a principal

Weigh a team default: strict equality surfaces shape drift early but fails on harmless class refactors, so decide which module outputs warrant it and say so in review guidance.

## Three matchers, three different questions Every Jest assertion starts with `expect(received)`, which returns an expectation object, and ends with a **matcher** that decides pass or fail. The three equality matchers look interchangeable on numbers and strings, which is exactly why they catch people out on objects. Each asks a different question: - **`toBe(expected)`**: are these the *same value*, judged by `Object.is`? - **`toEqual(expected)`**: do these hold the *same data*, compared recursively, with a few allowances? - **`toStrictEqual(expected)`**: do these hold the same data *and* the same structure and types? For primitives the first two agree; the Jest docs say outright that `toBe` and `toEqual` are equivalent for numbers. The difference appears as soon as the received value is an object, an array, a class instance or an error. Any of them can be inverted with `.not`, as in `expect(a).not.toBe(b)`. ## toBe: identity through Object.is `toBe` calls `Object.is(received, expected)`. For an object or an array that is a **reference** check: it passes only when both sides point to the very same instance. A pricing function that builds a fresh `{ amount: 10, currency: 'EUR' }` on every call will never be `toBe` a literal written in the test, however identical the fields. `Object.is` also differs from `===` on two edge values: - `NaN` is `Object.is`-equal to `NaN`, so `expect(NaN).toBe(NaN)` passes. - `-0` and `0` are *not* equal, so `expect(-0).toBe(0)` fails. `toEqual` and `toStrictEqual` compare primitives with `Object.is` as well, so they fail on it too. Floating-point totals are the other classic trap: `0.1 + 0.2` is `0.30000000000000004`, so `toBe(0.3)` fails. Use `toBeCloseTo(0.3)`, which by default checks two digits after the decimal point, meaning a difference below `0.005`. When `toBe` fails on two objects that are deeply equal, the failure output helps: it prints *If it should pass with deep equality, replace "toBe" with "toStrictEqual"* (or with `toEqual` when only the lenient comparison would pass), and, when both sides print identically, it reports that the received value *serializes to the same string*. ## toEqual: recursive, but forgiving `toEqual` performs **deep equality**: it compares objects key by key and arrays element by element, all the way down. The docs list the cases it deliberately ignores, and the source adds one about errors: 1. A key whose value is `undefined` is treated as missing, so `{ total: 10, discount: undefined }` equals `{ total: 10 }`. 2. Trailing `undefined` array items are ignored, so `[2]` equals `[2, undefined]`. 3. Array **sparseness** is ignored, so `[, 1]` equals `[undefined, 1]`. 4. **Object type** is ignored, so an instance of `class Price` with `amount: 5` equals the literal `{ amount: 5 }`. 5. Two `Error` objects are compared on `message` only, so an `Error` and a `TypeError` with the same text are equal. The docs recommend `toThrow` for asserting on errors. These allowances make `toEqual` the comfortable default for "is this the data I expected", and they are also how it hides a bug: an `undefined` field that will leak into a serialized response, or a plain object returned where callers rely on a class's methods. ## toStrictEqual: the same walk, no allowances `toStrictEqual` runs the same recursive comparison with extra checks for type, sparseness and `undefined`-valued keys. The table summarises what each matcher does with the usual suspects. | Received vs expected | `toBe` | `toEqual` | `toStrictEqual` | |---|---|---|---| | `{ a: 1 }` vs a separate `{ a: 1 }` | fails | passes | passes | | `{ a: 1, b: undefined }` vs `{ a: 1 }` | fails | passes | fails | | `[, 1]` vs `[undefined, 1]` | fails | passes | fails | | `new Price(5)` vs `{ amount: 5 }` | fails | passes | fails | | `new Error('x')` vs `new TypeError('x')` | fails | passes | fails | | the same reference on both sides | passes | passes | passes | | `-0` vs `0` | fails | fails | fails | ## Choosing the matcher A simple order of questions picks the right one: 1. Is it a primitive? Use `toBe`; for a float, use `toBeCloseTo`. 2. Must it be the very instance you passed in, such as a cache returning the stored object? Use `toBe`. 3. Is the exact shape the contract, such as a payload you serialize or a value another layer compares? Use `toStrictEqual`. 4. Do you only care about the data, whatever its class or `undefined` padding? Use `toEqual`. 5. Do only some fields matter? Reach for a partial matcher such as `toMatchObject`, which is a separate tool with its own rules. Interviewers ask this because the wrong choice fails in both directions: `toBe` on objects fails tests that should pass, and `toEqual` where the shape matters passes tests that should fail.

  • Why does `expect(0.1 + 0.2).toBe(0.3)` fail in Jest, and what should replace it?
    `0.1 + 0.2` evaluates to `0.30000000000000004`, and `Object.is` demands an exact match. `toBeCloseTo(0.3)` checks two digits after the decimal point by default, meaning a difference below `0.005`; pass a second argument such as `toBeCloseTo(0.3, 5)` for tighter precision. For a float nested inside an object compared with `toEqual`, use `expect.closeTo(0.3)` in that field.
  • Why can `toEqual` pass when comparing a plain `Error` with a `TypeError` that has the same message?
    When both sides are errors, the deep-equality check compares only `message`, so the class and any other fields are ignored. `toStrictEqual` adds a type check and fails. For code that throws, the docs point to `toThrow`, which can require an error class, a message substring or a pattern.

  • toBe compares objects field by field, just like toEqual.
  • toBe uses the == operator, so 1 and '1' are treated as equal.
  • toEqual fails when the received object has an extra key set to undefined.
  • A class instance and a plain object with the same fields fail toEqual.
  • toStrictEqual only adds an array-length check on top of toEqual.
open as a page

In Jest 30, why does toThrow need the call wrapped in a function, and what arguments narrow the expected error?

level: juniorimportance: must knowfreq 70%

basics

~20 s

toThrow has to call the code itself to catch the error; an unwrapped call throws before expect even runs. Pass a substring, a regex, an error class (instanceof) or an error object (equal message) to narrow the match.

open as a page

In Jest 30, how do toMatchObject and asymmetric matchers such as expect.objectContaining and expect.any assert only part of a result?

level: middleimportance: must knowfreq 60%

basics

~20 s

toMatchObject passes when the received object holds the expected properties, recursively, ignoring extras. Asymmetric matchers such as expect.any(Date) or expect.stringMatching(/^q_/) stand in for a single value inside toEqual or toMatchObject, so volatile fields need no exact value.

open as a page

In a Jest 30 test file, when do describe callbacks run, and how do test.only, test.skip, test.todo and test.each change what runs?

level: middleimportance: should knowfreq 50%

basics

~20 s

Jest runs every describe callback first, synchronously, to collect tests, then runs them. test.only focuses tests within that file, test.skip marks one skipped, test.todo records a body-less placeholder, and test.each generates a test per data row.

open as a page

A Jest 30 custom matcher registered with expect.extend works in one file, prints a wrong message under .not, and is not a function in other files. Why?

level: seniorimportance: should knowfreq 30%

basics

~20 s

A matcher returns { pass, message }, and under .not Jest fails when pass is true, so message must describe that case too, typically via this.isNot. expect.extend registers only in the calling file; move it into a setupFilesAfterEnv module.

open as a page

Which equality matcher would you make your team's Jest 30 default for API responses and domain objects, and when would you allow partial matching instead?

level: principalimportance: should knowfreq 33%

basics

~20 s

Default to an exact matcher over the whole object, ideally toStrictEqual, for anything crossing a trust boundary: partial matchers pass a leaked extra field such as a password hash. Allow partial matching only for "at least these fields" contracts.

open as a page