Snapshot testing

On this page 7

Snapshot testing is a software testing technique in which a test serializes the output of code, stores it as a reference file called a snapshot, and on every later run compares the new output with that stored reference, failing when they differ. In programming, it is a form of regression testing that answers one question cheaply: has the output changed since it was last approved?

The technique became popular through front-end tooling, where rendered component trees are long and tedious to assert by hand, but it applies equally to API responses, compiler output, generated configuration and command-line text. Its value lies in detecting unintended change, not in proving that the output is correct.

How snapshot testing works

A snapshot test follows a record, compare and update cycle. On the first run no reference exists, so the framework writes the serialized output to disk and the test passes. On subsequent runs the framework serializes the output again and performs a textual or structural diff against the stored file; any difference fails the test and shows the diff to the developer.

When a difference is intentional, the developer updates the snapshot with an explicit command, and the new file is committed alongside the code change. The snapshot file therefore becomes part of the version-controlled specification, and reviewers see output changes in the pull request just like source changes.

The table below lists the stages of the cycle and what happens at each one.

StageWhat the framework doesDeveloper action
First runWrites the serialized output as a new snapshotInspect and commit the file
Matching runCompares output with snapshot, finds no differenceNone
Mismatching runFails and prints a diffDecide whether the change is a bug
Intentional changeOverwrites snapshot on update commandReview the diff, commit the new file
Obsolete snapshotReports snapshots without a matching testDelete stale files
Stages of the snapshot testing cycle

Types of snapshots and serialization

Snapshots differ mainly in what is serialized and where it is stored. The serializer is the decisive component: it must produce stable, deterministic and readable output, because an unreadable snapshot cannot be reviewed and an unstable one fails at random.

VariantStored formTypical use
External file snapshotSeparate file next to the testLarge component trees, API payloads
Inline snapshotString literal written into the test sourceShort values that benefit from visibility
Visual snapshotImage compared pixel by pixel or perceptuallyUser interface appearance
Approval fileReceived and approved text filesLegacy code, reports, generated documents
Structured data snapshotNormalized JSON or YAMLService responses, configuration output
Common snapshot variants

Inline snapshots keep the expected value in the test itself, which makes small expectations easy to read in review. Visual regression snapshots compare screenshots instead of text and need a tolerance threshold, because font rendering and anti-aliasing vary across operating systems and graphics drivers. The older approval testing tradition, used with legacy code, follows the same idea under a different name.

Snapshot testing compared with other test types

Snapshot testing differs from conventional assertions in who states the expectation. In a classic unit test the developer writes the expected value before running the code; in a snapshot test the code produces the expectation and a human approves it after the fact. This reversal makes snapshots fast to create but weaker as a statement of intent.

TechniqueExpectation sourceMain strengthMain weakness
Snapshot testRecorded output, approved by a humanBroad coverage with little codeDoes not express intent
Assertion-based unit testWritten by the developerPrecise and self-documentingLaborious for large outputs
Property-based testingGeneral rules over generated inputsFinds edge casesRules can be hard to formulate
End-to-end testUser-level scenario outcomesValidates whole workflowsSlow and brittle
Mutation testingExisting tests judged by injected faultsMeasures test strengthComputationally expensive
Snapshot tests and related techniques

Snapshots work best as a complement to targeted assertions. A unit test should still assert the critical behavior, such as a computed total, while a snapshot guards the surrounding structure against accidental drift.

Writing reliable snapshot tests

Reliable snapshots are small, focused and deterministic. The most common source of flaky snapshots is volatile data: timestamps, random identifiers, memory addresses, unordered collections and locale-dependent formatting. These values must be normalized or masked before serialization, typically with property matchers or custom serializers that replace them with placeholders.

SituationRecommended practiceReason
Output contains timestampsReplace with a fixed placeholderPrevents failures on every run
Huge rendered treeSnapshot a smaller subcomponentKeeps diffs reviewable
Key business valueUse an explicit assertion as wellStates intent clearly
Rendering differs by platformGenerate visual snapshots in one containerRemoves environment noise
Continuous integration runFail on missing snapshotsStops silent creation of references
Situations and recommended snapshot practice

In continuous integration, frameworks should run in a mode that refuses to write new snapshots, so a forgotten file cannot be created automatically on the build server and pass unnoticed.

Limitations and common pitfalls

The biggest risk of snapshot testing is reflexive updating. When a change produces dozens of failing snapshots, developers are tempted to run the update command without reading the diffs, which turns the test suite into a rubber stamp that approves bugs together with intended changes.

  • Oversized snapshots of thousands of lines are never read carefully during review.
  • Snapshotting implementation details, such as internal class names, causes failures after harmless refactoring.
  • Recording a bug as the baseline makes the test protect incorrect behavior.
  • Nondeterministic output produces flaky failures that erode trust in the suite.
  • Treating snapshot count as coverage overstates how well behavior is verified.

Understanding it simply

Snapshot testing is like taking a photo of how something looks today so you can compare it with a new photo tomorrow. The first time, the computer saves a copy of the result. Every time after that, it checks whether the new result looks exactly the same.

If something changed, the test stops and shows the difference. A person then decides: was this change planned, or is it a mistake? The snapshot catches change, but a human decides whether the change is right.

Applied in practice

A front-end team maintains a design library of about 120 reusable interface components, including buttons, forms and navigation menus. Each component has a snapshot test that records its rendered markup for several states, such as disabled, loading and error.

A developer upgrades a shared styling helper and runs the test suite. Three button snapshots fail, and the diff shows that an accessibility attribute named aria-disabled has disappeared from disabled buttons. The change was not intended, so the developer fixes the helper instead of updating the snapshots.

In the same week, another developer deliberately changes a menu label, reviews the single failing diff, and commits the updated snapshot with the code. Reviewers see both changes in the pull request, and the accessibility regression never reaches users.