Snapshot Testing

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…

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();
  });
});

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.

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

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

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.

What you will learn