Jest · Unit tests that survive refactors

How does snapshot testing work in Jest?

EasysnapshotsregressionserializationUpdated Oct 2026
Quiz this track

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.

ts
test("formats the invoice summary", () => {
  const summary = renderInvoiceSummary({ total: 120, currency: "USD" });

  expect(summary).toMatchSnapshot();
});
The first run creates the snapshot; later runs compare against it.

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.

Snapshot files must be reviewed and committed. A snapshot that is regenerated in CI without human review can bless a regression. Treat a large snapshot diff as a code review item, not a formality.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1When should you prefer an explicit assertion over a snapshot?
  2. 2What does the -u flag do?
  3. 3Why should snapshot files be committed?
  4. 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.