Jest 14 ๐ Snapshot Testing โ toMatchSnapshot and Update Workflows
A snapshot test records a value on the first run and compares against it on every subsequent run. The matcher is expect(value).toMatchSnapshot(), and the stored value lives in a __snapshots__ directory next to the test file. The test fails when the current value differs from the stored one, and the failure shows a diff. The developer decides whether the change is intentional, and the -u flag rewrites the snapshot to match the new value. The mechanism is the same as Vitest’s, and the update workflow is the part that determines whether a snapshot test is useful or a rubber stamp.
This chapter covers the toMatchSnapshot matcher, the update workflow that makes a snapshot a reviewed decision, and the toMatchInlineSnapshot and toMatchFileSnapshot variants that change where the snapshot is stored. The sections that follow walk through the external snapshot, the update and CI behavior, and the inline and file variants.
Key point: toMatchSnapshot() writes a .snap file on the first run and compares on later runs; a failing snapshot is updated with -u/--update, and a CI run with --ci treats a missing snapshot as a failure rather than a write.
a. The external snapshot 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 "@jest/globals";
test("renders the user", () => {
const user = { id: "1", name: "Ana", email: "ana@example.com" };
expect(user).toMatchSnapshot();
});
The first run creates __snapshots__/user.test.js.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.
The React component snapshot is the original use case. The react-test-renderer produces a tree, and toMatchSnapshot() stores the tree. The test passes as long as the tree does not change, and the diff shows the markup change when it does.
b. The update workflow and the CI behavior
A failing snapshot is not a bug until the developer decides it is. The -u (--updateSnapshot) 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
jest -u
# Update in watch mode
jest --watch -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
jest --ci
The update workflow is the part that makes the snapshot a reviewed decision. The -u flag is for the local development, and the committed snapshot is the one that the reviewer sees in the pull request. A snapshot that is updated without the diff being reviewed is a snapshot that records whatever the code currently does, including the bug.
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 snapshotResolver option changes where the .snap files are written, which is the pattern for a project that keeps the snapshots in a different directory.
The obsolete snapshots are the cleanup. A snapshot for a test that no longer exists is obsolete, and the -u flag removes the obsolete snapshots. The check is the reason a test that is deleted leaves a stale snapshot behind unless the update runs.
c. The inline and file variants
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 summary", () => {
const summary = { total: 3, currency: "USD" };
expect(summary).toMatchInlineSnapshot(`
{
"currency": "USD",
"total": 3,
}
`);
});
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 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.
test("renders the page", async () => {
const html = "<html><body>Hello</body></html>";
await expect(html).toMatchFileSnapshot("./__snapshots__/page.html");
});
The toMatchFileSnapshot is asynchronous, and the test must await it. The file path is relative to the test file, and the file is written on the first run and compared on later runs.
The property matchers are the way to make a snapshot tolerant of a value that changes. A toMatchSnapshot with a expect.any(Date) inside the object passes when the date is any date, which is the pattern for a snapshot that should not change on every run.
expect({
id: "1",
createdAt: new Date(),
}).toMatchSnapshot({
createdAt: expect.any(Date),
});
Complete Example Session
// ============================================
// PART 1: THE EXTERNAL SNAPSHOT
// ============================================
test("renders the user", () => {
const user = { id: "1", name: "Ana", email: "ana@example.com" };
expect(user).toMatchSnapshot();
});
// First run: writes __snapshots__/user.test.js.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
// ============================================
// jest -u
// rewrites the snapshots to the current values
// ============================================
// PART 5: THE CI BEHAVIOR
// ============================================
// jest --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
| Matcher | Writes To |
|---|---|
toMatchSnapshot() | __snapshots__/*.snap |
toMatchInlineSnapshot() | The test file |
toMatchFileSnapshot(path) | The given file |
Flags
| Flag | Effect |
|---|---|
-u / --updateSnapshot | Rewrite snapshots |
--ci | Missing snapshot is a failure |
Config
| Option | Effect |
|---|---|
snapshotFormat | Serialization options |
snapshotResolver | Snapshot location |
ci | CI behavior |
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
jest --ci // โ
โ Don’t Do This:
// Snapshot the whole DOM for a large page
expect(page).toMatchSnapshot(); // unreviewable // โ
// Update without reviewing the diff
jest -u # blindly accept // โ
// Commit without a snapshot
// (CI fails with --ci) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Snapshot written in CI | No --ci | Add the flag |
| Snapshot updated unintentionally | -u in the test script | Keep -u out of CI |
| Large unreviewable snapshot | Whole page snapshotted | Snapshot the data, not the DOM |
| Obsolete snapshot left | Test deleted | Run -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
jest -u
6. CI
jest --ci
7. Property matcher inside a snapshot
expect({ id: "1", createdAt: new Date() }).toMatchSnapshot({
createdAt: expect.any(Date),
});
8. Snapshot a string
expect(message).toMatchSnapshot();
9. Snapshot an array
expect(items).toMatchSnapshot();
10. Snapshot format
module.exports = { 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 โ
โ โ โ โ
โ โผ โผ โ
โ jest -u fix the code โ
โ commit re-run โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| External snapshot | toMatchSnapshot() |
| Inline snapshot | toMatchInlineSnapshot() |
| File snapshot | toMatchFileSnapshot(path) |
| Update | -u / --updateSnapshot |
| CI | --ci fails on missing |
| Snapshot location | __snapshots__/ |
Key takeaways:
toMatchSnapshotwrites to a.snapfile;toMatchInlineSnapshotwrites 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
-uflag accepts the change, and the review is what makes the acceptance safe. --citurns 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-formatrenders 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.
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!