← Back to Jest Mastery
Intermediate16 min read

Snapshot Testing

Capture serialized output snapshots for components, objects, and API responses.

Creating Snapshots

expect(value).toMatchSnapshot() serializes value to a .snap file on first run. Subsequent runs compare output—mismatch fails test.

Snapshots work for React component trees (with react-test-renderer or RTL container), JSON API responses, and error messages.

import { render } from "@testing-library/react";
import { Button } from "./Button";

test("renders primary button", () => {
  const { container } = render(<Button variant="primary">Save</Button>);
  expect(container.firstChild).toMatchSnapshot();
});

Updating Snapshots

Intentional UI changes require snapshot updates via jest -u or --updateSnapshot. Review diff carefully in PR—snapshot updates should be deliberate, not bulk-approved.

Inline snapshots (toMatchInlineSnapshot) store expected output in test file—convenient for small strings, noisy for large trees.

  • Never update all snapshots blindly to green CI
  • Pair snapshot tests with behavioral assertions
  • Use property matchers to ignore dynamic ids in snapshots
expect(formatCurrency(1234.5)).toMatchInlineSnapshot(`"$1,234.50"`);

Snapshot Diff Review

Jest shows colorized diff on failure. Snap files group by test file in __snapshots__ directory. Commit snap files to version control.

Large snapshots are review fatigue—prefer smaller scoped snapshots or explicit assertions for complex UIs.

expect(data).toMatchSnapshot({
  id: expect.any(String),
  createdAt: expect.any(String),
});

When to Use Snapshots

Good for stable serialized output—CLI help text, config objects, simple component markup. Poor sole test for behavior—clicks, state changes, and accessibility need interaction assertions.

Replace snapshot-only tests over time with RTL queries as team matures testing culture.

  • Avoid snapshots of entire pages—break into components
  • Serialize with stable sort order for object keys
  • Delete obsolete snapshots when tests removed—jest --ci catches orphans

Snapshot Alternatives

Visual regression tools (Playwright, Chromatic) compare pixels for UI. Explicit expect assertions on roles and text survive refactors better than markup snapshots.

For API contracts, JSON schema validation or contract tests beat snapshots when consumers depend on shape.

  • Use toMatchSnapshot with custom serializers for domain types
  • Consider approval tests pattern for large legacy outputs
  • Document snapshot policy in team testing guidelines

Get In Touch


Ready to discuss your next project? Drop me a message.