A teammate tidies the CSS and accidentally removes the class btn-primary from the Buy button. Every test stays green, because all they check is that the text "Buy" is there. Nobody sees the change until a buyer wonders why the button looks different.
Snapshot testing catches changes like this. A snapshot test stores a "photo" of some output, for example the HTML a component renders. At every later run, the new output is compared with that photo. If they differ, the test fails, and you decide: was the change on purpose, or is it a bug? Picture photographing a shop shelf before closing. The next morning you compare the shelf with the photo, and anything that moved is seen right away. But the photo can't tell what was moved on purpose from what went missing. That's your job. In this picture, the shelf is your component's output, the photo is the snapshot, and comparing the shelf with the photo is the next test run.
Record once, compare every run
The example in this lesson is a buy button component, BuyButton. The Lab uses the same button with Indonesian names: TombolBeli, the text Beli (Buy), and the class btn-utama where this lesson uses btn-main.
// BuyButton.jsx
export function BuyButton() {
return (
<button className="btn btn-primary" type="button">
Buy
</button>
);
}
The test renders that button, then compares it with the snapshot:
// BuyButton.test.jsx
import { describe, it, expect } from "vitest";
import { render } from "@testing-library/react";
import { BuyButton } from "./BuyButton";
describe("BuyButton", () => {
it("matches the design", () => {
const { container } = render(<BuyButton />);
expect(container.firstChild).toMatchSnapshot();
});
});
render(...)returnscontainer, the element wrapping what was rendered.container.firstChildis the<button>.toMatchSnapshot()compares that element with the stored snapshot.- The first run has no snapshot yet, so Vitest writes it and the test passes. The report says
Snapshots 1 written. - The exception is CI, a server that runs tests automatically (for example GitHub Actions, which sets
CI=true). There Vitest writes no new snapshot, so a test that has no snapshot yet fails, with the messageSnapshot...mismatched(does not match) andSnapshots 1 failed. So run the tests once on your laptop, then commit (save in git) the__snapshots__folder that holds the snapshots. Never use-u(the command that rewrites snapshots, explained below) in CI.
The snapshot is stored in a __snapshots__ folder next to the test file, and is committed to git with it:
// __snapshots__/BuyButton.test.jsx.snap
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`BuyButton > matches the design 1`] = `
<button
class="btn btn-primary"
type="button"
>
Buy
</button>
`;
The attributes are sorted alphabetically, one per line. className in JSX is recorded as class, because the photo is of the DOM, not of the JSX code.
For short output there's toMatchInlineSnapshot(). Vitest writes the photo right inside the test file. So the photo is easy to read when someone checks your pull request (a request to merge your changes):
expect(container.firstChild).toMatchInlineSnapshot(`
<button
class="btn btn-primary"
type="button"
>
Buy
</button>
`);
When it fails: read the diff, then decide
Say the class btn-primary is changed to btn-main. The next run gives:
FAIL BuyButton.test.jsx > BuyButton > matches the design
Error: Snapshot `BuyButton > matches the design 1` mismatched
- Expected
+ Received
<button
- class="btn btn-primary"
+ class="btn btn-main"
type="button"
>
Buy
</button>
The lower part of this message is called the diff: a list of the lines that differ.
- Lines with
-are in the old snapshot, and lines with+are in the new render. Lines with no sign are the same in both. - The snapshot only says "different". It can't tell which one is right.
So read the diff first. If the change is the one you meant, update the snapshot:
npx vitest --update
-u is its short form, and in watch mode you just press u. The report says Snapshots 1 updated. In this example, the switch to btn-main is on purpose, so the right step is to update the snapshot, not to delete the test. If the diff shows something you did not change, it's a bug: fix the code, don't update.
Values that change every run
A component that puts a clock, a date or a random id in its HTML makes the snapshot fail on every run, even when the code didn't change. For example, this random id:
<button id={`buy-${Math.random().toString(36).slice(2, 6)}`} ...>
Every render has a different id, so the test is always red. There are two fixes. Pin the value in the test, so it is always the same: vi.useFakeTimers() and vi.setSystemTime(...) (which sets a fixed date and time) for time, and a mock for random numbers. Or keep that value out of the snapshot.
When a snapshot fits
- Fits: small, stable output whose changes should be deliberate, such as one small component's markup (its HTML), a validation error message, or a config object.
- Fits poorly: business logic, your app's calculation rules (
expect(calculateDiscount(200)).toBe(180)is far clearer), big pages hundreds of lines long, and data that keeps changing.
The biggest risk: big snapshots that change often get developers used to pressing -u without reading the diff. Unintended changes get saved along with the rest, and the test stops guarding anything. A snapshot detects change, it doesn't prove correctness. So use snapshots alongside ordinary assertions.
⚠️ Snapshots that stop guarding anything
- Updating without reading the diff.
npx vitest -uaccepts every change, bugs included. - A snapshot of a whole page. The diff is too long to read, so it just gets updated.
- Random values or time in the output. The snapshot fails every run. Pin the value first.
- A snapshot as the only test. A snapshot also passes for HTML that was wrong from the start, if the wrong version is what got recorded.
TL;DR: A snapshot test records an output (for example the HTML a component renders) once, like a photo. It is stored with toMatchSnapshot() in a .snap file in the __snapshots__ folder, or with toMatchInlineSnapshot() right in the test file. The output of every later run is compared with that record. When it fails, read the diff (the lines that differ: - the old snapshot, + the new output). If the change is deliberate, update with npx vitest --update (or -u). If not, fix the code. Values that change every run (time, random ids) must be pinned so they stay the same. The main risk is developers getting used to updating without reading the changes. So use small snapshots for stable output, alongside ordinary assertions.
⚡ Record once, compare every run
Write:
it("matches the design", () => {
const { container } = render(<BuyButton />);
expect(container.firstChild).toMatchSnapshot();
});
Meaning: A snapshot test stores a "photo" of an output, then compares every later run with that photo. Here render draws the component BuyButton (a Buy button), and container.firstChild is its <button> element. The first run has no snapshot yet, so Vitest writes it to the __snapshots__ folder (Snapshots 1 written).
⚡ When it fails: read the diff, then decide
Write:
npx vitest --update
Guess first: the button's class is changed from btn-primary to btn-main on purpose, and the snapshot goes red. Update the snapshot, or delete the test?
Update. The change is deliberate, so record the new photo with npx vitest --update (or -u).
Meaning: npx vitest --update rewrites the snapshot with the new result. Before that, read the diff (the lines that differ). If the diff shows something you did not change, it's a bug: fix the code, don't update.
⚡ The biggest risk of snapshots
Meaning: Big snapshots that change often get developers used to pressing -u without reading the diff, so unintended changes get saved too. Use small snapshots for stable output, alongside ordinary assertions.