A snapshot test records output on the first run and compares it on later runs. It is cheap to write and easy to abuse: a large snapshot is approved without reading it, then updated blindly when it fails, so it stops asserting anything meaningful.
Before you start
You should be comfortable with a test framework that supports snapshots. This article focuses on when snapshots add value; it assumes basic assertion skills.
Step-by-step walkthrough
Step 1: Snapshot stable, serializable output
Snapshots suit values that are stable and readable: a formatted string, a small configuration object, or a serialized message. Timestamps, random ids and DOM structures make a snapshot churn on every run, which trains reviewers to ignore it.
Step 2: Keep snapshots small and focused
Assert a small slice rather than a whole component tree. A five-line snapshot can be read in review; a five-hundred-line one cannot. Prefer explicit assertions for the fields that matter and a snapshot for the shape around them.
Step 3: Treat a diff as a decision
When a snapshot changes, the diff is the test output: read it and decide whether the change is intended. Updating snapshots with the update flag without reading is the failure mode that makes the test worthless.
Worked scenario
An inline snapshot keeps the expected value visible next to the assertion.
function formatPrice(cents) {
return `$${(cents / 100).toFixed(2)}`;
}
test('formats price', () => {
expect(formatPrice(1234)).toMatchInlineSnapshot('"$12.34"');
});Walk through the example
The inline snapshot stores the expected string in the test file, so a reviewer sees both the input and the expected output without opening a separate file. Changing formatPrice produces a clear one-line diff, small enough to judge. A separate .snap file with hundreds of lines would have the same content but far less review value.
Common mistake
Updating snapshots with the framework’s flag as part of routine work, which approves whatever the code now produces. Another is snapshotting a component whose markup changes for unrelated reasons, so the test fails constantly and gets muted.
Verify the behavior
Change the formatter and confirm the snapshot fails with a readable diff. Run with the update flag deliberately and inspect the diff before accepting it. Temporarily add a timestamp to the output and observe the churn it causes, which is why volatile values should be mocked or excluded.
Interview exercise
When should you avoid a snapshot test?
Answer and reasoning
Avoid it when the output is large, volatile or hard to read, or when only a few fields matter. In those cases explicit assertions state the intent and fail with a useful message. Snapshots are best for small, stable shapes where the whole value is meaningful and a reviewer can actually read the diff.
Continue learning
Compare assertion styles in Behavior assertions and Arrange, act, assert. Read the Jest snapshot testing documentation and try the Testing interview questions.