Skip to content

Assertions and Matchers

Master expect, toBe, toEqual, toThrow, and custom matchers for precise checks.

What you'll learn

  • The difference between identity, equality, and deep equality assertions
  • Using matchers for numbers, strings, arrays, and objects
  • Asserting exceptions with toThrow and toReject
  • Negating and chaining matchers safely

Concept

The Heart of a Test

An assertion is the line that actually decides pass or fail. In Jest and Vitest, assertions start with expect(actual) and chain a matcher that compares it to an expected value. Choosing the right matcher is what makes a test precise: too loose and it hides bugs, too strict and it breaks on harmless changes.

Identity vs Equality

toBe uses Object.is — it checks reference identity for objects and exact value for primitives. toEqual performs a deep recursive equality check, comparing every field of objects and every element of arrays. Use toBe for primitives and references you want to be the same object; use toEqual (or the stricter toStrictEqual) for comparing data structures you built.

Specialized Matchers

There are matchers for almost every need: toBeGreaterThan, toBeCloseTo (for floats), toMatch (regex), toContain (substring or array element), toHaveLength, toHaveProperty, toThrow (sync errors), and rejects.toThrow (async rejections). toBeCloseTo is essential for floating point — never use toBe on the result of arithmetic with decimals.

Negation and Custom Matchers

Every matcher can be negated with .not, but use negation sparingly — not.toBe(undefined) is weaker than toBeDefined(). When a domain check repeats across tests, extract it into a custom matcher so the assertion reads naturally and the failure message is helpful. Good matchers produce failure messages that explain exactly what went wrong.

In Practice

The matcher you choose communicates intent to the reader and shapes the failure message you get when the test breaks. Prefer the most specific matcher available: toHaveLength(3) is clearer than expect(arr.length).toBe(3), and toContainEqual(item) conveys "this item is in the array" better than a manual find. For objects, toMatchObject checks a subset of fields, which is more resilient than toEqual when new fields are added — choose the strictness that matches what you actually care about. When a domain concept repeats (e.g. "this date is within business hours"), register a custom matcher with expect.extend so tests read as prose and failure messages are domain-specific rather than generic. Reading the matcher documentation once end-to-end pays off every day thereafter.

Example

              import { describe, it, expect } from "vitest";

describe("matcher examples", () => {
  it("compares primitives and structures", () => {
    expect(2 + 2).toBe(4);              // identity
    expect({ a: 1, b: 2 }).toEqual({ a: 1, b: 2 }); // deep equal
    expect([1, 2, 3]).toContain(2);     // membership
    expect("hello world").toMatch(/world/); // regex
  });

  it("checks floating point safely", () => {
    expect(0.1 + 0.2).toBeCloseTo(0.3, 5); // NOT toBe — float error
  });

  it("asserts exceptions", () => {
    const parse = () => JSON.parse("{bad}");
    expect(parse).toThrow(SyntaxError);
  });
});
            

Each matcher communicates intent. toBeCloseTo with a precision argument avoids the classic 0.1+0.2 floating point trap that toBe would fail on.

Try it

  • Regex Tester

    Build and verify the regex patterns you pass to toMatch.

  • JSON Diff

    Visualize the deep-equality differences toEqual reports.

Common mistakes

The mistake

Using toBe on floating point results

The fix

Floating point arithmetic introduces tiny errors. Use toBeCloseTo(expected, precision) for any test involving decimals.

The mistake

Overusing .not matchers

The fix

Prefer positive matchers (toBeDefined, toBeNull) over .not.toBe(undefined). Positive assertions give clearer failure messages.

Practice Assertions and Matchers

17 exercises

Practice Assertions and Matchers

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors