← Concepts

阅读中文版本

Snapshot Testing

Snapshot testing records the output of a function and fails on change, so a deliberate output update is a visible, reviewed diff rather than a silent behavior shift.

testing

Definition

Snapshot testing is a technique where the output of a function or component is serialized and stored as a fixture; subsequent runs compare against the fixture and fail on any difference, so that an output change is a reviewable diff that a human must explicitly accept rather than a silent regression.

Context and scope

Applied in UI component testing, serialization stability, and any function whose output is large, stable, and where a change should be reviewed.

Common misconceptions

  • Snapshot tests are just golden files — they are golden files with a framework-managed fixture and a diff workflow; the mechanism is the same
  • Snapshots replace assertion writing — they replace explicit assertions for one output; they do not replace testing behavior, and a snapshot of the wrong output pins the wrong behavior

Anti-patterns

  • Snapshotting output that includes a timestamp or random value, so the snapshot changes every run and the test is flaky
  • Auto-updating snapshots in CI without review, so any output change is accepted and the test stops catching regressions

Related concepts

Authoritative source

https://jestjs.io/docs/snapshot-testing

What it is

Snapshot testing is a technique where the output of a function or component is serialized and stored as a fixture; subsequent runs compare against the fixture and fail on any difference, so that an output change is a reviewable diff that a human must explicitly accept rather than a silent regression. Applied in UI component testing, serialization stability, and any function whose output is large, stable, and where a change should be reviewed. The distinguishing question is what counts as evidence: a test that passes by accident is worse than no test, because it manufactures false confidence that propagates into release decisions.

How it works

Sound tests exercise a specific behavior contract, isolate the unit under test from environmental noise, and fail with a diagnostic that points at the cause rather than the symptom. Determinism is engineered, not assumed: clocks are fixed, randomness is seeded, and external state is replaced with doubles whose interactions are asserted, not merely stubbed. Coverage measures which behaviors were exercised, not which lines were visited.

When to apply and pitfalls

Apply where the cost of an undetected regression exceeds the cost of writing and maintaining the test. The recurring pitfall is testing the implementation rather than the behavior — such tests break on every refactor and teach nothing. Equally damaging are tests that assert only the happy path, leaving the error branches — where most production bugs live — unexercised.