JavaScriptMedium
What is Snapshot Testing?
Snapshot testing saves the serialised output of something (rendered component markup, a data structure, an error message) to a file on the first run, and on later runs fails if the output differs, so unexpected changes are caught and reviewed.
How it works
expect(value).toMatchSnapshot()writes a.snapfile the first time.- Later runs compare the new output with the stored snapshot.
- If the change is intended, update it (
-u/--update) and commit the new snapshot; if not, you found a regression. - Inline snapshots (
toMatchInlineSnapshot()) store the expected value directly in the test file, which keeps small snapshots readable in code review.
Good uses
- Small, stable outputs: serialised config, generated code, CLI output, error messages, transformed data.
- Catching accidental changes in a component's structure as a supplement to behavioural tests.
- Visual regression testing (Playwright
toHaveScreenshot, Chromatic) is the image-based relative, which is great for design systems.
Common problems
- Huge snapshots that nobody reads, so updates get approved blindly with
-u. - Brittle tests that fail on harmless markup or class-name changes.
- False confidence: a snapshot asserts "same as before", not "correct".
- Non-deterministic output (dates, random ids) causes flaky failures. Use fixed values or property matchers (
expect.any(String)).
Best practice
Keep snapshots small and focused, prefer explicit assertions for behaviour ("shows an error when the email is invalid"), review snapshot diffs like code, and never update snapshots without reading the diff.
Code example
js
1// format.js2export function formatInvoice({ id, customer, items, issuedAt }) {3 const total = items.reduce((s, i) => s + i.price * i.qty, 0);4 return {5 title: `Invoice #${id} for ${customer}`,6 lines: items.map((i) => `${i.qty} x ${i.name} @ ${i.price.toFixed(2)}`),7 total: total.toFixed(2),8 issuedAt,9 };10}1112// format.test.js (Vitest / Jest)13import { test, expect } from "vitest";14import { formatInvoice } from "./format.js";1516test("formats an invoice", () => {17 const invoice = formatInvoice({18 id: 42,19 customer: "Ada",20 items: [{ name: "Book", price: 12.5, qty: 2 }],21 issuedAt: new Date().toISOString(), // non-deterministic!22 });2324 // Small inline snapshot + property matcher for the changing field25 expect(invoice).toMatchInlineSnapshot(26 { issuedAt: expect.any(String) },27 `28 {29 "issuedAt": Any<String>,30 "lines": [31 "2 x Book @ 12.50",32 ],33 "title": "Invoice #42 for Ada",34 "total": "25.00",35 }36 `37 );38});
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.