Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 30 ยท Snapshots and Tables

Snapshot Testing

Learn Jest snapshot testing: toMatchSnapshot, toMatchInlineSnapshot, updating with -u, property matchers, and when snapshots help or hurt, with a runnable snapshot-store stand-in.

Some outputs are big: a rendered component, a generated report, an error message list, a parsed syntax tree. Writing expect(output).toEqual({ ... }) by hand for fifty fields is tedious, and keeping it current is worse.

Snapshot testing flips the work around. The first time a test runs, Jest saves the output (the "snapshot") to a file. On every later run, Jest compares the new output with the saved one and fails if they differ. You do not write the expected value; you review it once, commit it, and let Jest guard it from then on.

Snapshots are powerful and easy to misuse. This lesson shows how they work, how to update them safely, and how to decide when a snapshot is the right tool. The real toMatchSnapshot needs Jest, so the Jest code is read-only. A runnable stand-in builds a miniature snapshot store so you can watch the whole lifecycle.

The snapshot lifecycle

First run No snapshot yet, so Jest writes one.
Later runs Output must equal the saved snapshot.
A difference The test fails and shows a diff.
Update Run with -u if the change is intended.

Review every snapshot change like a code change.

1 / 2

Your first snapshot

Suppose a function builds a summary of an order:

JavaScript
function describeOrder(order) {
  return {
    id: order.id,
    lines: order.items.map((item) => `${item.qty} x ${item.name}`),
    total: order.items.reduce((sum, item) => sum + item.qty * item.price, 0),
  };
}

A snapshot test looks like this:

JavaScript
test("describes an order", () => {
  const order = {
    id: 42,
    items: [
      { name: "Pen", qty: 2, price: 3 },
      { name: "Notebook", qty: 1, price: 12 },
    ],
  };

  expect(describeOrder(order)).toMatchSnapshot();
});

The first run passes, because there was nothing to compare against, and Jest writes a file next to the test:

TEXT
__snapshots__/orders.test.js.snap

with content similar to this:

JavaScript
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing

exports[`describes an order 1`] = `
{
  "id": 42,
  "lines": [
    "2 x Pen",
    "1 x Notebook",
  ],
  "total": 18,
}
`;

The key is the test's full name plus a counter. The value is the output run through a serializer (pretty-format), which prints objects, arrays, dates, maps and so on in a stable, readable way. Commit this file to git together with the test. A teammate who changes describeOrder will see the test fail until the snapshot is reviewed and updated.

When the output changes, Jest prints a diff:

TEXT
- Snapshot  - 1
+ Received  + 1

    "lines": [
-     "2 x Pen",
+     "2 ร— Pen",

Updating snapshots

If the change is intentional, regenerate the snapshot:

CONSOLE
$ npx jest -u                    # update every failing snapshot
$ npx jest orders -u             # only tests in files matching "orders"
$ npx jest --watch               # press "u" to update failures interactively

The flag is -u or --updateSnapshot. Treat it with care. It does not ask whether the new output is correct; it just accepts it. Always look at the diff of the .snap file in your pull request. Running jest -u blindly to make a red build green defeats the purpose.

In a continuous integration environment, Jest runs with --ci, which refuses to write new snapshots, so a missing snapshot fails instead of silently passing. This catches the case where someone forgot to commit the .snap file.

Snapshots for tests that no longer exist are called obsolete. Jest reports them, and running with -u removes them. Remember to commit the cleanup.

Inline snapshots

Instead of a separate file, toMatchInlineSnapshot writes the snapshot into your test:

JavaScript
test("describes an order (inline)", () => {
  expect(describeOrder({ id: 1, items: [{ name: "Pen", qty: 2, price: 3 }] }))
    .toMatchInlineSnapshot();
});

After the first run, Jest rewrites your source file so the call contains the value:

JavaScript
expect(describeOrder({ id: 1, items: [{ name: "Pen", qty: 2, price: 3 }] }))
  .toMatchInlineSnapshot(`
{
  "id": 1,
  "lines": [
    "2 x Pen",
  ],
  "total": 6,
}
`);

Inline snapshots keep the expectation next to the test, so reviewers see both at once. They suit small outputs. Jest needs prettier available to format the inserted text in many versions, so check the documentation for your setup.

Property matchers for unstable values

Some values change on every run: ids, timestamps, random tokens. A snapshot that contains them would fail every time. Replace them with matchers:

JavaScript
test("creates a user record", () => {
  const user = createUser("Ada");

  expect(user).toMatchSnapshot({
    id: expect.any(Number),
    createdAt: expect.any(Date),
  });
});

The snapshot stores Any<Number> and Any<Date> for those fields and the real values for the rest. Better still, make the code deterministic (inject the clock and the id generator, or fake the clock as in Mocking Timers, Dates and HTTP).

You can also check errors with toThrowErrorMatchingSnapshot(), which stores the error message.

When snapshots help, and when they harm

Snapshots shine when:

  • The output is large but structured and stable, like a serialized data structure or generated text.
  • You are adding tests to legacy code and want a quick safety net before refactoring. This is often called a characterization test.
  • A human reads the snapshot in code review and can tell whether the change is right.

Snapshots hurt when:

  • The snapshot is thousands of lines long. Nobody reads it, so the review is a rubber stamp.
  • It captures implementation detail, such as internal class names or every element of a rendered tree, so harmless refactors cause noisy failures.
  • The team gets used to running -u on every failure. A snapshot test is only as good as the attention paid when it changes.
  • You use it where a precise assertion is clearer. expect(total).toBe(18) says what matters; a snapshot of the whole object hides it.

A good rule: if you can state in a sentence what the test protects, write that assertion. Use a snapshot for the rest. Keep snapshots small and focused: snapshot the part of the output that is interesting, not the whole world. Our Common Matchers lesson lists the precise alternatives.

Stand-in: a snapshot store you can watch

Jest saves snapshots on disk and serializes them with pretty-format. The stand-in below keeps them in a Map (so the example is self-contained) and serializes with JSON.stringify. It is NOT Jest's implementation, but it follows the same rules: write on first run, compare on later runs, fail on a difference, and replace the stored value only when asked to update.

Node.js Snapshot lifecycle: write, match, fail, update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at run 3: the test fails and shows both versions, just as Jest's diff would. Run 4 plays the role of jest -u: it accepts the new output. And the last line shows why --ci is valuable: a missing snapshot is an error, not a silent pass.

Stand-in: property matchers

To hide values that change on each run, the snapshot must replace them with a placeholder before comparing. This stand-in does that by type name. It is a simplification of what expect.any(...) does inside a Jest snapshot.

Node.js Masking unstable fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Good snapshot habits

  • Commit .snap files and review their diffs.
  • Keep each snapshot small and named by a clear test title, so a failure explains itself.
  • Prefer inline snapshots for short output and file snapshots for long output.
  • Do not snapshot values that change on every run; mask them or make them deterministic.
  • Never update snapshots just to make a build pass. Read the diff first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens the very first time a toMatchSnapshot test runs and no snapshot exists yet (not in CI mode)?

    With nothing to compare against, Jest records the received value as the snapshot and the assertion passes.
  2. 2. Which command accepts all new output as the expected snapshots?

    -u (--updateSnapshot) rewrites the stored snapshots with the received output. Use it only after reviewing the diff.
  3. 3. A snapshot contains a timestamp that changes every run. What is the best fix?

    Property matchers replace unstable values with a placeholder, and a fake clock removes the instability at the source.
  4. 4. Why does Jest's --ci flag matter for snapshots?

    In CI mode a missing snapshot is an error instead of being quietly created, which catches uncommitted snapshot files.

Summary

  • toMatchSnapshot() saves the serialized output on the first run and compares against it on later runs.
  • Snapshot files live in __snapshots__ and belong in version control; toMatchInlineSnapshot() stores the value inside the test.
  • jest -u updates snapshots; review the diff before you accept it, and use --ci in pipelines.
  • Property matchers or deterministic inputs keep unstable values out of snapshots.
  • Snapshots suit large, stable, readable output; precise assertions are better for small facts.

Next, learn how to run the same test over many inputs in Table-Driven Tests with test.each.