| | |

Vitest 14 🧪 Snapshot Testing — toMatchSnapshot and toMatchInlineSnapshot

⏱️ Estimated read: 8 min | |

A snapshot test compares a value against a stored representation of a previous value. The first run writes the snapshot, and every subsequent run compares against it. If the value changed, the test fails and shows the diff, and the developer decides whether the change is intentional. The mechanism is the same as Jest’s, and the two matchers are the same: toMatchSnapshot writes the snapshot to a .snap file next to the test, and toMatchInlineSnapshot writes it into the test file itself.

This chapter covers the two matchers, the file layout that the snapshot files create, and the update and CI behavior that determines whether a snapshot is written or compared. The sections that follow walk through the external snapshot, the inline snapshot, and the --update and --ci flags that control the write path.

Key point: toMatchSnapshot() writes a .snap file on the first run and compares on later runs; toMatchInlineSnapshot() writes the value into the test file; a failing snapshot is updated with -u/--update, and in CI a missing snapshot is treated as a failure rather than a write.


a. toMatchSnapshot and the .snap file

expect(value).toMatchSnapshot() serializes the value, compares it to the stored snapshot, and writes the snapshot if none exists. The snapshot is stored in a __snapshots__ directory next to the test file, in a .snap file named after the test file.

import { test, expect } from "vitest";

test("renders the user", () => {
  const user = { id: "1", name: "Ana", email: "ana@example.com" };
  expect(user).toMatchSnapshot();
});

The first run creates __snapshots__/user.test.ts.snap with a serialized representation of the object. The second run reads the file, serializes the current value, and compares the two. A difference fails the test with a diff that shows the added and removed lines.

The snapshot name is derived from the test name, and a second toMatchSnapshot in the same test gets a 2 suffix. The toMatchSnapshot("custom name") form supplies an explicit name, which is useful when the test name changes or when the snapshot is shared across tests.

expect(user).toMatchSnapshot("user object");

The serialization is the pretty-format format, which renders objects, arrays, and JSX in a readable form. A Date is serialized as an ISO string, a Map and Set as their entries, and a function as [Function]. The serialization is deterministic for the same input, which is the property that makes the comparison meaningful.


b. toMatchInlineSnapshot and the test file

expect(value).toMatchInlineSnapshot() writes the snapshot into the test file as the argument to the matcher. The first run with an empty call writes the value, and the subsequent runs compare against it.

test("renders the user", () => {
  const user = { id: "1", name: "Ana" };
  expect(user).toMatchInlineSnapshot(`
    {
      "id": "1",
      "name": "Ana",
    }
  `);
});

The inline form has the advantage of being visible in the test file. A reviewer reading the test sees the expected value without opening a separate .snap file, which makes the snapshot reviewable in the pull request diff. The disadvantage is that the test file grows with the snapshots, and a large snapshot makes the test harder to read.

The toMatchInlineSnapshot with an explicit argument is the form for a test that needs a specific snapshot. The argument is compared, and a mismatch fails the test. The empty call is the form for the first write, and the -u flag fills it in.

The toMatchFileSnapshot matcher is the third form. It writes the snapshot to an arbitrary file, which is the pattern for a snapshot that is too large for the test file and too specific for the shared .snap file—a rendered HTML document, a generated JSON file, a SQL query.

await expect(html).toMatchFileSnapshot("./__snapshots__/page.html");

c. The update and CI behavior

A failing snapshot is not a bug until the developer decides it is. The -u (--update) flag rewrites the snapshots to match the current values, and the developer reviews the diff to confirm that the change is intentional.

# Update the snapshots
vitest run -u

# Update in watch mode
vitest -u

The --ci flag changes the behavior for a missing snapshot. Without it, a missing snapshot is written and the test passes. With it, a missing snapshot is treated as a failure, which is the correct behavior for CI: a snapshot that does not exist in the repository is a test that has never been reviewed.

# CI: missing snapshot is a failure
vitest run --ci

The snapshotFormat config option controls the serialization. The printBasicPrototype: false option removes the prototype from the printed object, and the escapeString: false option disables the string escaping. The resolveSnapshotPath option changes where the .snap files are written, which is the pattern for a project that keeps the snapshots in a different directory.

The obsoleteSnapshots check is the cleanup. A snapshot for a test that no longer exists is obsolete, and the --update flag removes the obsolete snapshots. The check is the reason a test that is deleted leaves a stale snapshot behind unless the update runs.


Complete Example Session

// ============================================
// PART 1: THE EXTERNAL SNAPSHOT
// ============================================
import { test, expect } from "vitest";

test("renders the user", () => {
  const user = { id: "1", name: "Ana", email: "ana@example.com" };
  expect(user).toMatchSnapshot();
});

// First run: writes __snapshots__/user.test.ts.snap
// Later runs: compares

// ============================================
// PART 2: THE INLINE SNAPSHOT
// ============================================
test("renders the summary", () => {
  const summary = { total: 3, currency: "USD" };
  expect(summary).toMatchInlineSnapshot(`
    {
      "currency": "USD",
      "total": 3,
    }
  `);
});

// ============================================
// PART 3: THE FILE SNAPSHOT
// ============================================
test("renders the page", async () => {
  const html = "<html><body>Hello</body></html>";
  await expect(html).toMatchFileSnapshot("./__snapshots__/page.html");
});

// ============================================
// PART 4: THE UPDATE
// ============================================
// vitest run -u
// rewrites the snapshots to the current values

// ============================================
// PART 5: THE CI BEHAVIOR
// ============================================
// vitest run --ci
// a missing snapshot is a failure, not a write

The parts covered the external snapshot, the inline snapshot, the file snapshot, the update flag, and the CI behavior.


Quick Reference

Matchers

MatcherWrites To
toMatchSnapshot()__snapshots__/*.snap
toMatchInlineSnapshot()The test file
toMatchFileSnapshot(path)The given file

Flags

FlagEffect
-u / --updateRewrite snapshots
--ciMissing snapshot is a failure

Config

OptionEffect
snapshotFormatSerialization options
resolveSnapshotPathSnapshot location
obsoleteSnapshotsDetect unused snapshots

Best Practices

✅ Do This:

// Use inline for small, reviewable snapshots
expect(summary).toMatchInlineSnapshot();                       // ✅

// Use the external file for large output
expect(user).toMatchSnapshot();                                // ✅

// Run with --ci in CI
vitest run --ci                                                // ✅

❌ Don’t Do This:

// Snapshot the whole DOM for a large page
expect(page).toMatchSnapshot(); // unreviewable                 // ❌

// Update without reviewing the diff
vitest -u # blindly accept                                     // ❌

// Commit without a snapshot
// (CI fails with --ci)                                        // ❌

Common Pitfalls

PitfallWhy It HappensFix
Snapshot written in CINo --ciAdd the flag
Snapshot updated unintentionally-u in the test scriptKeep -u out of CI
Large unreviewable snapshotWhole page snapshottedSnapshot the data, not the DOM
Obsolete snapshot leftTest deletedRun -u to clean up

Real-World Examples

1. External snapshot

expect(user).toMatchSnapshot();

2. Named snapshot

expect(user).toMatchSnapshot("user object");

3. Inline snapshot

expect(summary).toMatchInlineSnapshot();

4. File snapshot

await expect(html).toMatchFileSnapshot("./page.html");

5. Update

vitest run -u

6. CI

vitest run --ci

7. Property matcher inside a snapshot

expect({ ...user, id: expect.any(String) }).toMatchSnapshot();

8. Snapshot a string

expect(message).toMatchSnapshot();

9. Snapshot an array

expect(items).toMatchSnapshot();

10. Snapshot format

test: { snapshotFormat: { printBasicPrototype: false } }

Visual

The Snapshot Lifecycle

┌─────────────────────────────────────────────────────────┐
│  First run                                              │
│    toMatchSnapshot() → no snapshot → write → pass       │
│                                                         │
│  Later run                                              │
│    toMatchSnapshot() → snapshot exists → compare        │
│         │                                               │
│    ┌────┴────┐                                          │
│    ▼         ▼                                          │
│  match     differ                                       │
│    │         │                                          │
│    ▼         ▼                                          │
│  pass      fail with diff                               │
│                                                         │
│  Update: -u rewrites the snapshot                       │
└─────────────────────────────────────────────────────────┘

External vs Inline

┌─────────────────────────────────────────────────────────┐
│  EXTERNAL                       INLINE                  │
│  toMatchSnapshot()              toMatchInlineSnapshot() │
│    → __snapshots__/*.snap         → the test file        │
│    → separate file                → visible in the test  │
│    → large output                 → small, reviewable    │
└─────────────────────────────────────────────────────────┘

The CI Behavior

┌─────────────────────────────────────────────────────────┐
│  WITHOUT --ci                   WITH --ci               │
│                                                         │
│  Missing snapshot               Missing snapshot        │
│    → written                    → failure               │
│    → test passes                → CI fails               │
│                                                         │
│  Local development              CI                       │
└─────────────────────────────────────────────────────────┘

The Update

┌─────────────────────────────────────────────────────────┐
│  Test fails with a diff                                 │
│         │                                               │
│         ▼                                               │
│  Review the diff                                        │
│         │                                               │
│    ┌────┴────┐                                          │
│    ▼         ▼                                          │
│  intended  unintended                                   │
│    │         │                                          │
│    ▼         ▼                                          │
│  vitest -u  fix the code                                │
│  commit     re-run                                      │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
External snapshottoMatchSnapshot()
Inline snapshottoMatchInlineSnapshot()
File snapshottoMatchFileSnapshot(path)
Update-u / --update
CI--ci fails on missing
Snapshot location__snapshots__/

Key takeaways:

  • toMatchSnapshot writes to a .snap file; toMatchInlineSnapshot writes to the test file. The external file keeps the test readable for a large value, and the inline form keeps a small value reviewable in the diff.
  • A snapshot is a decision, not a bug. A failing snapshot shows a diff, and the developer decides whether the change is intentional. The -u flag accepts the change, and the review is what makes the acceptance safe.
  • --ci turns a missing snapshot into a failure. Without it, a missing snapshot is written and the test passes, which means a snapshot that was never reviewed can enter the repository.
  • The serialization is deterministic for the same input. pretty-format renders objects, arrays, and JSX in a stable form, which is what makes the comparison meaningful.
  • The obsolete snapshots are the cleanup. A snapshot for a deleted test is removed by the update run, and a project that never updates accumulates stale snapshots.

Remember: A snapshot is a stored expectation. The first run writes it, and every later run compares against it. The external file is for the large value, the inline form is for the small one, and the file snapshot is for the artifact that does not fit either. Run with --ci to catch the missing snapshot, and review the diff before -u accepts it. The snapshot is only as useful as the review that follows the change.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!