Jest · Unit tests that survive refactors
How does snapshot testing work in Jest?
Short answer
toMatchSnapshot serializes a value and stores it on the first run, then compares later runs. Snapshots catch unintended output changes but do not replace explicit behavioural assertions.
A snapshot is a committed artifact. On first run Jest writes the serialized value to a .snap file next to the test. On later runs it compares the new serialization and fails if it differs, which makes snapshots useful for stable serialized output such as a small rendered tree or an API response shape.
test("formats the invoice summary", () => {
const summary = renderInvoiceSummary({ total: 120, currency: "USD" });
expect(summary).toMatchSnapshot();
});Where snapshots fit
- Small, stable output that would be tedious to assert field by field
- Serialized API payloads where the shape is the contract
- Inline snapshots for short values that benefit from living in the test
- Not a substitute for checking user-visible behaviour or edge cases
A snapshot only says that output changed, not that it is correct. When a snapshot fails, read the diff and decide whether the change is intended. Running with -u rewrites every failing snapshot, which is useful while iterating but dangerous when done without review.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1When should you prefer an explicit assertion over a snapshot?
- 2What does the -u flag do?
- 3Why should snapshot files be committed?
- 4What is an inline snapshot?
Say it in the interview
toMatchSnapshot serializes a value the first time and compares against it later. I use it for small, stable output where the exact shape matters, like a serialized payload. When it fails I read the diff and decide whether the change is intended rather than blindly updating. A snapshot proves something changed, not that the behaviour is right, so I still assert important outcomes explicitly.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.