How-To Guide

How to Implement Snapshot Testing Safely

Use snapshots without rubber-stamping: snapshot stable output, review every change, keep snapshots small, and add assertions the snapshot cannot make.

On this page

  1. Introduction
  2. Snapshot only what is stable
  3. Keep the snapshot small and focused
  4. Review every change and update deliberately
  5. Add the assertions a snapshot cannot make
  6. Test that the snapshot still detects a change
  7. Common pitfalls
  8. Conclusion

Introduction

A snapshot test captures the output of a function and compares it against a stored copy on the next run. It is easy to write and covers a lot of output at once, and it is easy to make worthless: a snapshot that is updated whenever it changes agrees with whatever the code produced, so it detects nothing. The value of a snapshot is not the comparison but the review of the diff, which is where a real change is confirmed and an unintended one is caught.

This tutorial covers snapshotting stable output, keeping it small, reviewing every change, and adding the assertions a snapshot cannot make. The examples use a snapshot library, and the practice matches golden-file and approval testing.

Snapshot only what is stable

A snapshot compares the output across runs, so any variation makes it fail spuriously. Normalize the output first: replace a timestamp with a placeholder, a random id with a <ID>, a machine path with <ROOT>, and sort any collection so the order is fixed. Without normalization, the snapshot fails on a run-by-run difference and the team learns to update it blindly.

Snapshot the parts that are deterministic and worth pinning, such as the rendered markup, the serialized shape, or the formatted text. Leave out the parts that legitimately vary, or normalize them into a placeholder. A stable snapshot is the precondition for the diff to mean something, because an unstable one drowns the real change in noise.

function normalize(output) {
  return output
    .replace(/\d{4}-\d{2}-\d{2}T[\d:.]+Z/g, '<TIMESTAMP>')
    .replace(/id="[0-9a-f-]{36}"/g, 'id="<UUID>"');
}

test('renders the profile', () => {
  const html = normalize(renderProfile(aUser()));
  expect(html).toMatchSnapshot();   // stable, small, reviewable
});

Keep the snapshot small and focused

A snapshot of a whole page or a large tree hides the change in the diff, so a reviewer cannot tell what moved. Snapshot a focused output, such as a component, a serialized record, or a formatted message, so a change is a few lines and points at the cause. Several small snapshots are easier to review than one large one.

Prefer several snapshots scoped to the units that matter over one for everything. When one fails, the name says which unit, and the diff is small. A large snapshot that fails names nothing and dumps a large diff, which is exactly the case where a reviewer accepts the update without reading it.

Review every change and update deliberately

The snapshot is only as good as the review of its diff. When a snapshot changes, inspect the diff in the commit and confirm the change is intended; an unintended change is a caught bug. Never update the snapshot blindly, because that turns the test into a record of whatever the code did, which detects nothing.

Keep the update mode explicit and separate from the test run, so a change is a deliberate action that produces a diff for review. A snapshot update should be justified in the commit message or the pull request, like any code change. A snapshot that no one reviews is a snapshot that tests nothing.

Add the assertions a snapshot cannot make

A snapshot captures the output, not the properties it should have. It cannot say that the counter is non-negative, that the list is sorted, or that the total equals the sum of the items; it only says the output matches last time. For those, add a property assertion alongside the snapshot, so the semantics are checked and not only the exact bytes.

The snapshot covers the shape and the exact rendering, which is tedious to assert by hand; the explicit assertion covers the semantic property, which a snapshot cannot express. Use each for what it is good at: the snapshot for a broad, exact output, and the assertion for the invariant. Together they check both that the output is unchanged and that it is correct.

test('the order summary', () => {
  const summary = summarizeOrder(aOrder());
  expect(summary.total).toBe(summary.items.reduce((s, i) => s + i.price * i.qty, 0)); // invariant
  expect(normalize(JSON.stringify(summary))).toMatchSnapshot();                          // exact shape
});

Test that the snapshot still detects a change

Prove the snapshot test is meaningful by changing the output and asserting the test fails. If a change to the code does not fail the snapshot, the test is not comparing what you think, or it is being updated automatically. This meta-check is what catches a snapshot that has become a rubber stamp.

Also test that the normalization is stable: run the same input twice and assert the normalized output is identical, so the snapshot does not depend on the run. And test that a real difference, a field change, still shows in the diff, so normalization has not been so aggressive that it hides changes.

# change a rendered value and assert the snapshot test fails
# then add the change to the snapshot deliberately and review the diff in git
npx vitest run --no-update            # a real change must fail here
git diff test/__snapshots__/          # review the diff before accepting it

Common pitfalls

Snapshotting unstable output so it flakes, a large snapshot whose diff hides the change, updating the snapshot blindly so it tests nothing, relying on the snapshot for a semantic property it cannot express, and never proving the snapshot detects a change are the recurring mistakes. Normalization, small focused snapshots, reviewed updates, explicit property assertions, and a meta-check address them.

Conclusion

A snapshot test is worth its review, not its comparison. Snapshot stable, small output, review every change and update deliberately, add explicit assertions for the semantic properties, and prove the snapshot fails on a real change. Self-check by changing an output and asserting the test fails, and by asserting the normalization is stable across runs. Then the snapshot pins the exact output while the assertions check that it is correct.

Sources: Jest: Snapshot testing, Vitest: Snapshots, Approval testing (Wikipedia).

FAQ

What is the risk of snapshot testing?
A snapshot that is updated on every change agrees with whatever the code produced, so it tests nothing. The value is in the review of the diff: a change that is reviewed and intended is fine, and one that is not is a caught bug.
What should not be snapshot?
Output that varies between runs, such as a timestamp or a random id, unless it is normalized first, and large trees where a change is lost in the diff. Snapshot a stable, small output where the change is visible.

Related Examples