Jest 05 ๐ Matchers โ toBe, toEqual, toMatch, and toThrow
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
| Matcher | Asserts | Use For |
|---|---|---|
toBe(v) | Object.is | Primitives, same reference |
toEqual(v) | Deep equality | Objects, arrays |
toMatch(v) | String/regex match | Partial string assertions |
toThrow(v) | Function throws | Error assertions |
Equality Matchers
| Matcher | undefined Properties | Class Instances |
|---|---|---|
toEqual | Ignored | Match plain objects |
toStrictEqual | Must match | Must match |
toThrow Forms
| Form | Asserts |
|---|---|
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
| Pitfall | Why It Happens | Fix |
|---|---|---|
toBe fails on identical objects | Reference comparison | Use toEqual |
toEqual passes when a field is missing | undefined ignored | Use toStrictEqual |
toThrow does not catch | Called the function | Wrap in () => fn() |
| Removed matcher alias | Jest 30 cleanup | Use the new name |
| Array order not checked | toEqual checks order | Sort 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
| Item | Value |
|---|---|
| Primitive equality | toBe (Object.is) |
| Deep equality | toEqual (ignores undefined) |
| Strict deep equality | toStrictEqual |
| String matching | toMatch (string or regex) |
| Error assertion | toThrow with () => fn() wrapper |
| Array containment | toContain |
| Removed in Jest 30 | toThrowError (use toThrow) |
Key takeaways:
toBeisObject.is, not===. It treatsNaNas equal to itself and+0as different from-0, and it compares objects by reference. Two structurally identical objects failtoBe.toEqualis deep and ignoresundefined. It compares contents recursively, and a property with anundefinedvalue is treated as absent. UsetoStrictEqualwhen presence matters.toMatchtakes 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.toThrowneeds the function, not the call.expect(fn()).toThrow()callsfnbeforeexpectcan catch the throw. The wrapperexpect(() => fn()).toThrow()is the correct form.- Jest 30 removed the deprecated aliases.
toThrowErroris nowtoThrow. 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.
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!