Sub topic 12
Snapshot and Inline Snapshot Assertions
This chapter assumes you can write tests with test and expect and run Vitest in watch mode and single-run mode. A snapshot assertion saves the serialized output of a value the first time a test runs. Each later run compares the new output with the saved copy. Snapshots are useful when output is large or tedious to write by hand, such as formatted objects, generated strings, or rendered markup.
How a Snapshot Assertion Works
Vitest has two main forms:
| Matcher | Where the snapshot is stored |
|---|---|
| `toMatchSnapshot()` | A `.snap` file in a `__snapshots__` folder next to the test file |
| `toMatchInlineSnapshot()` | Written as a string argument into the test source itself |
Inline Snapshots
Start with an empty call:
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()
})After the first run, Vitest edits your test file so the call looks like this:
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 reviewer can read it without opening another file. Use inline snapshots for small outputs. Use toMatchSnapshot() for large ones that would clutter the test.
File Snapshots and Unstable Values
toMatchSnapshot() stores the output under a key built from the test name. Values that change on every run, such as timestamps or random IDs, break a snapshot. To handle them, pass a property matcher so those fields are checked by type instead of by value:
import { test, expect } from 'vitest'
function createOrder(item) {
return { item, id: Math.random().toString(36).slice(2), createdAt: new Date() }
}
test('creates an order', () => {
expect(createOrder('book')).toMatchSnapshot({
id: expect.any(String),
createdAt: expect.any(Date),
})
})Updating Snapshots on Purpose
When a snapshot fails, Vitest prints a diff. Read the diff before you do anything else. If the change is a bug, fix the code. If the change is intended, update the snapshot:
- Press
uin watch mode. - Run
npx vitest -u(or--update) for a single run.
Commit the snapshot changes together with the code change, so reviewers see both.
Common Errors
- Snapshotting huge objects. No one reviews a 300-line diff, so keep snapshots small and focused.
- Leaving dates, random values, or machine-specific paths in the output. Use property matchers, or remove those fields before taking the snapshot.
- Using a snapshot when one exact assertion would be clearer.
expect(total).toBe(42)states its intent better than a snapshot of42. - Deleting or renaming a test and leaving its old entry behind. Vitest reports obsolete snapshots, and
-uremoves them.
Exercise
A test using toMatchInlineSnapshot fails after you changed formatUser to return initials in lowercase on purpose. What should you do, and what should you check first?
Show answer
First read the diff Vitest prints and confirm that the only change is the lowercase initials. Then update the snapshot by pressing u in watch mode or running npx vitest -u. Commit the rewritten inline snapshot together with the code change.
Exercise
Why does a snapshot of an object that contains createdAt: new Date() fail on the second run, and how do you fix it without dropping the snapshot?
Show answer
The date is different on every run, so the serialized output never matches the saved copy. Pass a property matcher, such as toMatchSnapshot({ createdAt: expect.any(Date) }), so that field is checked by type and the rest is compared by value.