Skip to content
Latchkey

What Is Snapshot Testing?

Snapshot testing records a known-good version of some output and fails the test if a future run produces something different.

Snapshot testing trades hand-written assertions for an automatic baseline. The first run captures the output, a rendered component, a serialized object, an API response, into a stored snapshot. Later runs compare against it and flag any difference, so you notice unintended changes without writing detailed asserts.

How it works

On the first run, the test framework saves the output to a snapshot file committed to the repo. On subsequent runs it regenerates the output and diffs it against the saved snapshot. A match passes; a mismatch fails and shows the diff, asking you to confirm or reject the change.

Where it shines

  • Catching unintended changes in rendered UI components.
  • Locking down large serialized structures cheaply.
  • Reducing boilerplate for output-heavy tests.
  • Surfacing accidental formatting or structure drift.

Where it goes wrong

Snapshots can become a liability when they are large, opaque, or updated reflexively. A developer who runs "update all snapshots" without reading the diff turns a safety net into rubber-stamping. Keep snapshots small and review every change to them like real code.

A quick example

A component snapshot test renders the component and compares it to the stored baseline, failing if the markup changes.

A component snapshot test
test("renders button", () => {
  const tree = render(<Button label="Save" />);
  expect(tree).toMatchSnapshot();
});

Snapshot testing in CI

In CI, snapshots are read-only: the pipeline must fail on a mismatch rather than silently rewrite the baseline. Most frameworks support a ci flag that blocks snapshot writes. Running these tests on fast runners keeps the comparison cheap even for large snapshot sets.

Key takeaways

  • Snapshot testing diffs new output against a stored baseline.
  • It is great for catching unintended UI and structure changes.
  • In CI, snapshots must be read-only and updates reviewed carefully.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →