| | |

Jest 05 ๐Ÿƒ Matchers โ€” toBe, toEqual, toMatch, and toThrow

โฑ๏ธ Estimated read: 9 min | |

A Jest matcher is the assertion at the end of an expect call. It receives the expected value, compares it to the actual value, and either returns normally (pass) or throws an error (fail). Jest ships with more than thirty matchers, and the four that cover most assertions are toBe for primitive identity, toEqual for deep equality, toMatch for string and regex matching, and toThrow for error assertions. Choosing the right one determines whether the test fails for the right reason, and whether the failure message shows a useful diff.

This chapter covers the four core matchers, the equality distinctions that separate toBe from toEqual, and the error-assertion patterns that make toThrow catch the throw instead of triggering it. The sections that follow walk through the equality matchers, the string and error matchers, and the asymmetric matchers that compose with toEqual.

Key point: toBe uses Object.is and is for primitives; toEqual is deep equality and is for objects and arrays; toMatch takes a string or regex; toThrow needs the function passed as a wrapper (() => fn()) or it calls the function before expect can catch the throw.


a. toBe and toEqual: identity versus equality

toBe wraps Object.is. For primitives, it passes when the values are identical, with two exceptions: NaN equals itself, and +0 and -0 are not equal. For objects, arrays, and functions, it compares references, so two structurally identical objects fail toBe because they are different allocations.

// Primitives: pass when values are identical
expect(2 + 2).toBe(4);
expect("hello").toBe("hello");
expect(true).toBe(true);
expect(null).toBe(null);
expect(undefined).toBe(undefined);

// NaN equals itself
expect(NaN).toBe(NaN); // passes

// +0 and -0 are not equal
expect(0).not.toBe(-0); // passes (not equal)

// Objects: fail because references differ
const a = { x: 1 };
const b = { x: 1 };
expect(a).toBe(b); // fails โ€” different references
expect(a).toBe(a); // passes โ€” same reference

toEqual compares the values recursively. It checks that both values have the same type, the same keys (for objects), the same length and elements (for arrays), and recursively equal values at each position. It ignores undefined properties, which is the one rule that surprises people: { a: 1, b: undefined } is toEqual to { a: 1 }, because the b key with an undefined value is treated as absent.

// Objects: deep comparison
expect({ id: 1, name: "Ana" }).toEqual({ id: 1, name: "Ana" });

// Arrays: element-by-element
expect([1, 2, 3]).toEqual([1, 2, 3]);

// Nested structures
expect({ user: { id: 1, tags: ["a"] } }).toEqual({
  user: { id: 1, tags: ["a"] },
});

// undefined properties are ignored
expect({ a: 1, b: undefined }).toEqual({ a: 1 }); // passes

// Type distinctions matter
expect({ a: 1 }).not.toEqual({ a: "1" }); // number vs string
expect([1, 2]).not.toEqual([2, 1]); // order matters

The strict variant is toStrictEqual, which checks that the objects have the same type (class instances fail against plain objects), that undefined properties are present on both sides, and that sparse arrays have the same sparseness. Use it when the difference between “absent” and “present with undefined” matters.


b. toMatch and the string matchers

toMatch takes a string or a regular expression. A string argument passes when the actual string contains the expected substring; a regex argument passes when the regex matches. It is the matcher for partial string assertions, where the exact string is not known or not important.

// Substring match
expect("Jest is a test runner").toMatch("test runner");

// Regex match
expect("Jest is a test runner").toMatch(/test\s+runner/);

// Case-sensitive by default
expect("Jest").not.toMatch(/jest/);
expect("Jest").toMatch(/Jest/);

The string matchers that accompany toMatch are toContain for arrays and iterables (a different matcher), toHaveLength for arrays and strings, and stringContaining as an asymmetric matcher inside toEqual. The distinction is that toMatch asserts on a string, toContain asserts that an array includes an element, and expect.stringContaining asserts that a value inside an object is a string containing a substring.

// Array contains an element
expect([1, 2, 3]).toContain(2);

// String has a length
expect("hello").toHaveLength(5);

// Asymmetric matcher inside toEqual
expect({ message: "User not found" }).toEqual({
  message: expect.stringContaining("not found"),
});

c. toThrow and the error assertions

toThrow asserts that a function throws. The function must be passed as a wrapperโ€”expect(() => fn()).toThrow()โ€”because expect(fn()).toThrow() calls fn before expect receives the value, and the error propagates instead of being caught.

// Correct: wrapper defers the call
expect(() => divide(1, 0)).toThrow();

// With a message substring
expect(() => divide(1, 0)).toThrow("Division by zero");

// With a regex
expect(() => divide(1, 0)).toThrow(/division/i);

// With an error class
expect(() => divide(1, 0)).toThrow(Error);

// With an exact message (since Jest 27)
expect(() => divide(1, 0)).toThrow(
  new Error("Division by zero")
);

The toThrow matcher also supports an error-matching object: toThrow({ message: "Division by zero" }). The variants that were removed in Jest 30 are toThrowError, toThrowErrorMatchingSnapshot, and toThrowErrorMatchingInlineSnapshot; the replacements are toThrow, toThrowErrorMatchingSnapshot, and toThrowErrorMatchingInlineSnapshot with the same behavior but the shortened name.

The toThrow assertion fails if the function does not throw, and it fails if the function throws a different error than the one expected. A test that asserts toThrow("Division by zero") fails when the function throws a TypeError with a different message, which is the correct behavior: the test is checking the specific error, not any error.


Complete Example Session

// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/math.js
function add(a, b) {
  return a + b;
}

function divide(a, b) {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}

function greet(name) {
  return `Hello, ${name}!`;
}

module.exports = { add, divide, greet };

// ============================================
// PART 2: toBe FOR PRIMITIVES
// ============================================
const { add, divide, greet } = require("./math");

test("adds two numbers", () => {
  expect(add(1, 2)).toBe(3);
});

test("returns a string", () => {
  expect(typeof add(1, 2)).toBe("number");
});

// ============================================
// PART 3: toEqual FOR OBJECTS
// ============================================
test("returns an object with the right shape", () => {
  const result = { sum: add(1, 2) };
  expect(result).toEqual({ sum: 3 });
});

// ============================================
// PART 4: toMatch FOR STRINGS
// ============================================
test("greets by name", () => {
  expect(greet("Ana")).toMatch("Ana");
  expect(greet("Ana")).toMatch(/Hello, \w+!/);
});

// ============================================
// PART 5: toThrow FOR ERRORS
// ============================================
test("throws on division by zero", () => {
  expect(() => divide(1, 0)).toThrow("Division by zero");
  expect(() => divide(1, 0)).toThrow(Error);
  expect(() => divide(1, 0)).toThrow(/division/i);
});

The parts covered toBe for primitives, toEqual for objects, toMatch for strings, and toThrow with the three argument forms.


Quick Reference

The Four Core Matchers

MatcherAssertsUse For
toBe(v)Object.isPrimitives, same reference
toEqual(v)Deep equalityObjects, arrays
toMatch(v)String/regex matchPartial string assertions
toThrow(v)Function throwsError assertions

Equality Matchers

Matcherundefined PropertiesClass Instances
toEqualIgnoredMatch plain objects
toStrictEqualMust matchMust match

toThrow Forms

FormAsserts
toThrow()Any throw
toThrow("msg")Message contains substring
toThrow(/re/)Message matches regex
toThrow(ErrorClass)Error is instance of class
toThrow(new Error("msg"))Exact message

Best Practices

โœ… Do This:

// Primitives with toBe
expect(add(1, 2)).toBe(3);                                    // โœ…

// Objects with toEqual
expect(result).toEqual({ sum: 3 });                           // โœ…

// Strings with toMatch
expect(greet("Ana")).toMatch("Ana");                          // โœ…

// Errors with the wrapper
expect(() => divide(1, 0)).toThrow("Division by zero");       // โœ…

โŒ Don’t Do This:

// toBe for objects
expect({ a: 1 }).toBe({ a: 1 }); // always fails                // โŒ

// toThrow without the wrapper
expect(divide(1, 0)).toThrow(); // throws before expect         // โŒ

// toEqual when presence matters
expect({ a: 1, b: undefined }).toEqual({ a: 1 }); // hides bug  // โŒ

// Removed matcher alias
expect(fn).toThrowError(); // removed in Jest 30                // โŒ

Common Pitfalls

PitfallWhy It HappensFix
toBe fails on identical objectsReference comparisonUse toEqual
toEqual passes when a field is missingundefined ignoredUse toStrictEqual
toThrow does not catchCalled the functionWrap in () => fn()
Removed matcher aliasJest 30 cleanupUse the new name
Array order not checkedtoEqual checks orderSort or use arrayContaining

Real-World Examples

1. Primitive comparison

expect(count).toBe(3);

2. Deep object comparison

expect(user).toEqual({ id: 1, name: "Ana" });

3. Strict comparison

expect(obj).toStrictEqual({ a: 1 });

4. String match

expect(greeting).toMatch(/Hello/);

5. Error throw

expect(() => fn()).toThrow("message");

6. Error class

expect(() => fn()).toThrow(TypeError);

7. Array contain

expect([1, 2, 3]).toContain(2);

8. Array length

expect(items).toHaveLength(3);

9. Asymmetric matcher

expect(user).toEqual({ id: expect.any(Number) });

10. Floating point

expect(0.1 + 0.2).toBeCloseTo(0.3);

Visual

toBe vs toEqual

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  toBe: Object.is                                        โ”‚
โ”‚  {a:1} โ”€โ”€โ–บ reference A                                  โ”‚
โ”‚  {a:1} โ”€โ”€โ–บ reference B                                  โ”‚
โ”‚  A !== B โ†’ FAIL                                         โ”‚
โ”‚                                                         โ”‚
โ”‚  toEqual: deep                                          โ”‚
โ”‚  {a:1} โ”€โ”€โ–บ keys equal, values equal                     โ”‚
โ”‚  โ†’ PASS                                                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

toThrow Needs the Wrapper

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  WRONG                                                  โ”‚
โ”‚  expect(divide(1, 0)).toThrow()                         โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  divide throws before expect receives a value           โ”‚
โ”‚  The test fails with the thrown error, not the assertionโ”‚
โ”‚                                                         โ”‚
โ”‚  RIGHT                                                  โ”‚
โ”‚  expect(() => divide(1, 0)).toThrow()                   โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  expect calls the wrapper, catches the throw            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Matcher Selection

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Is the value a primitive?                              โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”                                          โ”‚
โ”‚    โ–ผ         โ–ผ                                          โ”‚
โ”‚   YES        NO                                         โ”‚
โ”‚    โ”‚         โ”‚                                          โ”‚
โ”‚    โ–ผ         โ–ผ                                          โ”‚
โ”‚  toBe     Is it a string?                               โ”‚
โ”‚               โ”‚                                         โ”‚
โ”‚          โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”                                    โ”‚
โ”‚          โ–ผ         โ–ผ                                    โ”‚
โ”‚         YES        NO                                   โ”‚
โ”‚          โ”‚         โ”‚                                    โ”‚
โ”‚          โ–ผ         โ–ผ                                    โ”‚
โ”‚       toMatch    toEqual                                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

toEqual vs toStrictEqual

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  const obj = { a: 1, b: undefined }                     โ”‚
โ”‚                                                         โ”‚
โ”‚  toEqual({ a: 1 })                                      โ”‚
โ”‚    โ†’ b ignored โ†’ PASS                                   โ”‚
โ”‚                                                         โ”‚
โ”‚  toStrictEqual({ a: 1 })                                โ”‚
โ”‚    โ†’ b present but not in expected โ†’ FAIL               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Primitive equalitytoBe (Object.is)
Deep equalitytoEqual (ignores undefined)
Strict deep equalitytoStrictEqual
String matchingtoMatch (string or regex)
Error assertiontoThrow with () => fn() wrapper
Array containmenttoContain
Removed in Jest 30toThrowError (use toThrow)

Key takeaways:

  • toBe is Object.is, not ===. It treats NaN as equal to itself and +0 as different from -0, and it compares objects by reference. Two structurally identical objects fail toBe.
  • toEqual is deep and ignores undefined. It compares contents recursively, and a property with an undefined value is treated as absent. Use toStrictEqual when presence matters.
  • toMatch takes a string or a regex. The string form is a substring match; the regex form is a pattern match. It is the matcher for partial string assertions.
  • toThrow needs the function, not the call. expect(fn()).toThrow() calls fn before expect can catch the throw. The wrapper expect(() => fn()).toThrow() is the correct form.
  • Jest 30 removed the deprecated aliases. toThrowError is now toThrow. A test that uses the old name fails with an error naming the replacement.

Remember: A matcher is the assertion, and the choice of matcher determines whether the test fails for the right reason. Use toBe for primitives, toEqual for structures, toMatch for strings, and toThrow with the arrow wrapper for errors. Use toStrictEqual when a missing field must fail, and toContain when the assertion is about array membership rather than equality. The failure message shows a diff for toEqual and a thrown error for toThrow; both are only useful if the matcher matches the intent.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!