SkillByAIOpen interactive version →

Lesson 19 / 25

Snapshot Testing and When to Avoid It

toMatchSnapshot, inline snapshots and review discipline.

A snapshot is a change detector

toMatchSnapshot() serialises a value (often rendered HTML) to a .snap file on the first run and compares against it afterwards; toMatchInlineSnapshot() writes the snapshot into the test file itself. Updating is one flag (-u, or u in watch mode), which is the danger: large snapshots of whole components get approved without review, fail on every harmless markup change and say nothing about which behaviour matters. Good uses: small, stable outputs such as a serialised config, an error message, a generated SQL string or a data transformation, preferably inline so reviewers see them. For components, prefer explicit assertions on what the user sees.

Tools that help, used with judgement

Snapshots, custom render wrappers and coverage reports are powerful, and each has a common misuse.

Figure 7.1 — Snapshot carefully, wrap with providers, read coverage critically.

A focused inline snapshot

The serialised value lives next to the test.

import { expect, it } from 'vitest';
import { buildSearchQuery } from './search';

it('builds the search query string', () => {
  expect(buildSearchQuery({ q: 'tea', tags: ['green', 'loose'], page: 2 }))
    .toMatchInlineSnapshot(`"q=tea&tags=green%2Cloose&page=2"`);
});

// avoid: a 300-line snapshot of an entire page that nobody reads
// it('renders', () => {
//   const { container } = render(<CheckoutPage />);
//   expect(container).toMatchSnapshot();
// });

// update snapshots after an intended change (review the diff first!):
//   npx vitest -u        npx jest -u

Review snapshot diffs like code

Treat changes to .snap files as real code review items. If nobody can say whether a snapshot diff is correct, the snapshot is too big to be useful.

Quick check: When is a snapshot test most useful?

  • For values that include the current timestamp
  • For the full HTML of every page
  • As a replacement for all assertions
  • For a small, stable serialised output that reviewers can actually read
Answer

For a small, stable serialised output that reviewers can actually read — Keep snapshots small and intentional.