Snapshot Testing Explained: How It Works, When It Helps and When It Hurts
Snapshot testing saves the output of your code once, then fails whenever the output changes. Learn how snapshots are created, how to read the diff, how to handle timestamps, and the review habits that stop snapshots from becoming rubber stamps.
- Snapshot testing stores a known-good output, then compares every later run against it and shows a diff when it changes.
- It is fast to write and great for large, structured outputs such as JSON responses, reports and rendered markup.
- Dynamic values like timestamps break snapshots. In our run, an unmasked timestamp failed on the very next run.
- The danger is blind updates. A snapshot only protects you if someone reads the diff before accepting it.
Writing assertions for a 40-field JSON response is tedious, and most people check five fields and hope for the best. Snapshot testing takes a different approach: run the code once, save the whole output to a file, and from then on fail the test whenever the output differs. You trade precise assertions for broad change detection, which is powerful when used with care.
We ran a working demo with pytest 9.2.0, the syrupy 7.0.0 snapshot plugin and Python 3.13.6. All outputs below are copied from those runs. Jest and visual screenshot snapshots are described for comparison but were not run. If pytest itself is new to you, start with our pytest tutorial.
What is snapshot testing?
A snapshot test has no hand-written expected value. The first time it runs, the tool records the actual output as the expectation and stores it next to your tests. Every later run compares the new output with that stored snapshot:
- If they match, the test passes.
- If they differ, the test fails and prints a diff.
- If the change is intended, you update the snapshot with one command and commit the new file.
So a snapshot test does not say the output is correct. It says the output is unchanged. Correctness is checked once, by a person, when the snapshot is first reviewed.
Types of snapshots
| Type | What is stored | Typical tools |
|---|---|---|
| Data snapshot | Serialised objects, JSON, text | syrupy, Jest, Vitest, Verify |
| Markup snapshot | Rendered HTML or component tree | Jest with React, Vue test utils |
| Visual snapshot | Screenshot image of a page or component | Playwright, Percy, Chromatic |
This guide focuses on data snapshots, because they are the easiest to start with and the easiest to review.
Our demo setup
# invoice.py
def render_invoice(items, now=None):
now = now or datetime.now(timezone.utc)
total = sum(q * p for _, q, p in items)
return {"generated_at": now.isoformat(),
"lines": [{"sku": s, "qty": q, "price": p} for s, q, p in items],
"total": round(total * 1.18, 2), "currency": "INR"}
def receipt_text(items):
rows = [f"{s:<6}{q:>3} x {p:>7.2f}" for s, q, p in items]
return "\n".join(rows + ["-" * 20, f"TOTAL {sum(q*p for _, q, p in items):>14.2f}"])
# test_invoice.py
ITEMS = [("PEN", 2, 20.0), ("INK", 1, 50.0)]
def test_receipt_text(snapshot):
assert receipt_text(ITEMS) == snapshot
def test_invoice_fixed_clock(snapshot):
assert render_invoice(ITEMS, now=datetime(2026, 11, 12, tzinfo=timezone.utc)) == snapshot
def test_invoice_masked_time(snapshot):
assert render_invoice(ITEMS) == snapshot(matcher=path_type({"generated_at": (str,)}))
The snapshot argument is a pytest fixture provided by syrupy. Our pytest fixtures guide explains how fixtures are injected like this.
The first run
$ pytest -q
3 failed
$ pytest -q --snapshot-update
3 snapshots generated.
3 passed
$ pytest -q
3 snapshots passed.
3 passed
With no stored snapshots, all three tests failed. That default is deliberate: a brand-new snapshot should be created on purpose, not silently. The update flag wrote the snapshots, and the next normal run passed.
What the snapshot file looks like
syrupy saved a readable file in a __snapshots__ folder. Part of it:
# name: test_invoice_fixed_clock
dict({
'currency': 'INR',
'generated_at': '2026-11-12T00:00:00+00:00',
'lines': list([
dict({
'price': 20.0,
'qty': 2,
'sku': 'PEN',
}),
...
]),
'total': 106.2,
})
This file is now your expected result, so review it like code. Is 106.2 right? Two pens at 20 plus one ink at 50 is 90, and 90 with 18% tax is 106.2, so yes. That one-time check is the moment snapshot testing depends on. Commit the file with the test.
What a code change looks like
Next we changed one word in the receipt, TOTAL to Total, and ran the tests again:
E AssertionError: assert [+ received] == [- snapshot]
E - TOTAL 90.00
E + Total 90.00
1 snapshot failed. 2 snapshots passed.
The diff pointed at the exact line that changed. If the change was intended, you update the snapshot. If not, you have caught a regression without ever writing an assertion about that label. This makes snapshots useful on output that other systems parse, such as receipts, CSV exports and API payloads. Our regression testing checklist covers where else such checks fit.
Timestamps, IDs and other moving parts
We added a test that snapshotted render_invoice with the real clock. It passed when the snapshot was created and failed on the very next run:
E - 'generated_at': '2026-11-12T15:12:34.206809+00:00',
E + 'generated_at': '2026-11-12T15:12:35.621553+00:00',
1 snapshot failed.
Any value that changes between runs makes a snapshot useless: times, random IDs, UUIDs, memory addresses, unordered sets. We used two fixes, and both passed reliably:
- Control the input: pass a fixed clock, as in
test_invoice_fixed_clock. This is the cleanest option. - Mask the field: syrupy’s
path_typematcher stored'generated_at': str, checking only the type.
Also sort lists whose order does not matter, and seed random data. Our test data generation guide shows how to make generated data repeatable.
Tip: if a snapshot fails on a rerun with no code change, treat it as a flaky test. Find the moving value and pin it; do not just regenerate the snapshot.
Updating snapshots safely
The update command is both the best and worst feature. It makes intended changes cheap, and it makes careless approval cheap too. Good habits:
- Never run the update flag to “make CI green” without reading the diff first.
- Commit snapshot changes in the same pull request as the code that caused them, so reviewers see both.
- Keep snapshots small. A 2,000-line snapshot diff will be skimmed, not reviewed.
- Delete obsolete snapshots; syrupy reported and removed one when we deleted its test.
- In CI, run without the update flag so new or changed snapshots fail instead of being written.
When snapshot testing helps
- Large, structured outputs where hand-written assertions would be long: API responses, reports, configuration generators.
- Refactoring code that has few tests. Snapshot the current behaviour first, then refactor and confirm nothing changed.
- Serialisers and formatters, where any change is probably important.
- Error messages and CLI output that users or scripts depend on.
For API payloads shared with other teams, combine snapshots with schema checks. Our API contract testing guide covers the contract side.
When snapshot testing hurts
- When the output changes often by design. Constant updates teach the team to approve without reading.
- When the logic is what matters. A tax rule deserves an explicit assertion with a named expected value, not a line inside a snapshot.
- When snapshots are huge. Nobody reviews them, so they lock in bugs as easily as correct behaviour.
- For visual snapshots across machines, where fonts and rendering differ unless you run in a fixed environment.
Jest, Vitest and visual snapshots
In JavaScript, Jest and Vitest use expect(value).toMatchSnapshot() and update with -u. They also offer inline snapshots, where the stored value is written into the test file itself, which keeps small snapshots visible during review. Playwright compares screenshots with toHaveScreenshot(), as introduced in our Playwright tutorial. We did not run these here, but they follow the same create, compare and update cycle shown above.
A snapshot review checklist
- Does the new snapshot contain the values you expect, checked by hand at least once?
- Does every changed line in the diff match the intended code change?
- Are there any timestamps, IDs or random values left unmasked?
- Is the snapshot small enough to read in a minute?
- Would an explicit assertion express the important rule more clearly?
Final thoughts
Snapshot testing is a fast way to detect unexpected changes in large outputs. Our demo showed both sides: a one-word change was caught with a precise diff, and an unmasked timestamp broke the test on the next run. Keep snapshots small, pin or mask moving values, review every update, and use explicit assertions for the rules that matter most.
Frequently asked questions
What is snapshot testing?
It stores the output of code from a known-good run and fails later runs when the output changes, showing a diff. It detects change rather than proving correctness.
How do I update a snapshot?
Run the tool’s update command, such as pytest with –snapshot-update for syrupy or jest -u. Read the diff first and commit the new snapshot with the code change.
Why do my snapshot tests fail on every run?
The output contains changing values such as timestamps, random IDs or unordered data. Pass a fixed clock, seed randomness, sort lists or mask those fields with a matcher.
Are snapshot tests good or bad?
They are useful for large structured outputs and refactoring, but harmful when huge or updated without review. Use explicit assertions for important business rules.
What is the difference between snapshot and visual testing?
Data snapshots store text or serialised values. Visual testing stores screenshots and compares pixels, which also catches layout and styling changes but is more sensitive to the environment.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.