Sub topic 12
Snapshot and Inline Snapshot Assertions
Most matchers make you write the expected value yourself: expect(add(2, 3)).toBe(5). That works well for small values. It gets tedious for large objects, formatted strings, error messages, or rendered markup, where typing out the expected result is slow and easy to get wrong. A snapshot assertion takes a different approach. The first run records the actual value, and every later run compares the new value against that recording.
This chapter assumes you know expect and its common matchers, how describe and test name tests, and how to run Vitest in watch mode and single-run mode.
How a Snapshot Assertion Works
A snapshot is a serialized copy of a value that Vitest stores and compares against on later runs. Vitest serializes the value with a pretty-format printer. Objects, arrays, strings, Maps, Sets, errors, and DOM nodes all become readable text. Vitest then does one of three things:
- No stored snapshot exists. Vitest writes one and the test passes. In CI (when the
CIenvironment variable is set), Vitest does not write it. The test fails, so a missing snapshot cannot slip through unnoticed. - A stored snapshot exists and matches. The test passes.
- A stored snapshot exists and differs. The test fails and Vitest prints a diff. It never overwrites the stored snapshot unless you ask it to.
A snapshot only says "this output has not changed." It does not say the output is correct. You check correctness when you read the snapshot the first time it is written, and again each time you accept an update.
File Snapshots with toMatchSnapshot
toMatchSnapshot() stores the snapshot in a separate file. For user.test.js, Vitest writes __snapshots__/user.test.js.snap next to the test file.
// user.test.js
import { describe, it, expect } from 'vitest'
function formatUser(user) {
return {
displayName: `${user.first} ${user.last}`,
initials: `${user.first[0]}${user.last[0]}`,
tags: new Set(user.tags),
}
}
describe('formatUser', () => {
it('builds display fields', () => {
expect(formatUser({ first: 'Ada', last: 'Lovelace', tags: ['math'] })).toMatchSnapshot()
})
})After the first run, the .snap file contains:
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`formatUser > builds display fields 1`] = `
{
"displayName": "Ada Lovelace",
"initials": "AL",
"tags": Set {
"math",
},
}
`;The key is the full test name, made from the describe and test names, followed by a counter. If one test calls toMatchSnapshot() twice, the stored entries end in 1 and 2. You can also pass a hint string, as in toMatchSnapshot('after login'), which goes into the key and makes the entry easier to find.
Commit .snap files to version control. They are part of the test. A reviewer should see snapshot changes in the same pull request as the code that caused them.
Inline Snapshots with toMatchInlineSnapshot
toMatchInlineSnapshot() stores the snapshot inside the test file. You write the call with no arguments:
import { test, expect } from 'vitest'
function formatUser(user) {
return { displayName: `${user.first} ${user.last}`, initials: `${user.first[0]}${user.last[0]}` }
}
test('formats a user', () => {
expect(formatUser({ first: 'Ada', last: 'Lovelace' })).toMatchInlineSnapshot()
})On the first run, Vitest edits your source file and fills in the argument:
import { test, expect } from 'vitest'
function formatUser(user) {
return { displayName: `${user.first} ${user.last}`, initials: `${user.first[0]}${user.last[0]}` }
}
test('formats a user', () => {
expect(formatUser({ first: 'Ada', last: 'Lovelace' })).toMatchInlineSnapshot(`
{
"displayName": "Ada Lovelace",
"initials": "AL",
}
`)
})The expected value now sits next to the code that produces it, so a reader does not have to open a second file. Vitest strips the shared indentation before comparing, which means re-indenting the test file does not break the snapshot.
Choosing between file and inline snapshots
| Concern | `toMatchSnapshot` | `toMatchInlineSnapshot` |
|---|---|---|
| Where the value lives | `__snapshots__/*.snap` | Inside the test source |
| Best size | Large output (markup, long reports) | Small to medium values |
| Readability of the test | Reader must open another file | Expected value is visible in place |
| Review in pull requests | Separate file diff | Diff inside the test file |
| Called repeatedly with different values | Supported, the counter separates entries | Fails, because one call site holds one literal |
A useful rule: if the snapshot fits on a screen, put it inline. If it does not fit, ask whether you need all of it before moving it to a file.
Updating Snapshots on Purpose
When you change behavior on purpose, the snapshot goes stale and the test fails. You update it in one of three ways:
- In watch mode, press
uto update the failing snapshots. - Run
npx vitest -u(or--update) to update every failing snapshot in that run. - Narrow the run first, for example
npx vitest -u user.test.js, so you only update what you meant to.
Read the diff before you update. If the diff shows a change you did not expect, you have found a bug, and updating would record that bug as correct.
Update mode also cleans up. When you rename or delete a test, its stored entry becomes obsolete. Vitest reports obsolete snapshots in the summary, and -u removes them.
Handling Values That Change Every Run
Timestamps, random IDs, and generated tokens differ on every run, so a plain snapshot of them always fails. You have three options.
The first option is a property matcher. Pass an object of asymmetric matchers as the first argument. Vitest checks those properties against the matchers and writes the matcher's name into the snapshot in place of the value:
import { test, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
function createOrder(item) {
return { id: randomUUID(), item, createdAt: new Date(), status: 'pending' }
}
test('creates a pending order', () => {
expect(createOrder('book')).toMatchInlineSnapshot(
{ id: expect.any(String), createdAt: expect.any(Date) },
`
{
"createdAt": Any<Date>,
"id": Any<String>,
"item": "book",
"status": "pending",
}
`,
)
})The second option is to make the value deterministic: use fake timers with vi.setSystemTime, or inject the ID generator as a dependency. The third option is to snapshot a smaller piece of the value, leaving the unstable fields out.
Snapshotting Errors
toThrowErrorMatchingInlineSnapshot() and toThrowErrorMatchingSnapshot() record the error message, which is convenient for long validation messages:
import { test, expect } from 'vitest'
function parseAge(input) {
const n = Number(input)
if (!Number.isInteger(n) || n < 0) {
throw new Error(`Invalid age "${input}": expected a non-negative integer`)
}
return n
}
test('rejects a negative age', () => {
expect(() => parseAge('-3')).toThrowErrorMatchingInlineSnapshot(
`[Error: Invalid age "-3": expected a non-negative integer]`,
)
})For async code, combine snapshots with rejects: await expect(promise).rejects.toThrowErrorMatchingInlineSnapshot().
Snapshots Stored as Real Files
toMatchFileSnapshot(path) writes the raw string to a file you name, with no serialization. Use it when the output is HTML, CSS, or JSON and you want syntax highlighting when you open the file. The matcher is asynchronous, so await it:
import { test, expect } from 'vitest'
function renderBadge(label) {
return `<span class="badge">${label}</span>\n`
}
test('renders a badge', async () => {
await expect(renderBadge('new')).toMatchFileSnapshot('./__snapshots__/badge.html')
})Common Mistakes
- Snapshotting everything. A 300-line snapshot of a whole component tree fails on every unrelated change, and reviewers stop reading it. Snapshot the part the test is about.
- Treating the first write as a pass. The first run always passes. Read what was written.
- Inline snapshots inside loops or
test.each. One call site can hold only one literal, so a call that runs several times with different values fails. UsetoMatchSnapshotthere, or explicit matchers. - Concurrent tests. In
test.concurrent, use theexpectfrom the test context (async ({ expect }) => ...) so each snapshot is linked to the right test. - Snapshots instead of intent.
expect(total).toBe(42)tells the reader what matters. A snapshot of the whole cart tells them less. Prefer explicit matchers for the one or two values the test is really about.
Exercise
A test calls expect(buildReport()).toMatchSnapshot(). You changed the report's footer on purpose and the test now fails. What do you do before running vitest -u, and what does -u do to the snapshot of a test you deleted last week?
Show answer
Read the printed diff and confirm that the only change is the intended footer change. If it is, run npx vitest -u (ideally limited to that test file) to rewrite the stored snapshot. Update mode also removes obsolete entries, so the snapshot belonging to the deleted test is removed from the .snap file.
Exercise
expect(createSession()).toMatchInlineSnapshot() fails on every run because the session has a random token string and an expiresAt Date. Write the assertion so the snapshot stays stable while still checking the types of those fields.
Show answer
Pass property matchers as the first argument: expect(createSession()).toMatchInlineSnapshot({ token: expect.any(String), expiresAt: expect.any(Date) }). On the next run Vitest records Any<String> and Any<Date> in place of the values. Another approach is to use fake timers with vi.setSystemTime and inject a fixed token generator so the values are deterministic.
Exercise
Why would toMatchInlineSnapshot() inside a test.each that runs three rows with different inputs fail, and what should you use instead?
Show answer
An inline snapshot is a single literal at a single call site. The three rows produce three different values, and they cannot all match one literal. Use toMatchSnapshot(), which stores a separate entry per test name (each row gets its own name), or use explicit matchers such as toEqual with an expected value taken from the row.