Snapshot Testing with Vitest: Inline Snapshots, Custom Serializers, and Component Testing
Snapshot testing records the output of a function or component and fails future runs if that output changes. When used well, it catches unintended regressions. When used poorly, it creates a pile of meaningless .snap files that developers blindly update whenever CI fails. This guide covers how Vitest implements snapshots, where it diverges from Jest, and the patterns that make snapshot testing actually useful.
Vitest vs Jest Snapshot Differences
Vitest's snapshot implementation is intentionally close to Jest's, which means most Jest snapshot tests migrate with zero changes. Under the hood, both use @vitest/snapshot (Vitest) and jest-snapshot respectively — same serialization format, same .snap file layout. But there are meaningful differences:
Snapshot storage location. Jest places .snap files in a __snapshots__ directory adjacent to the test file. Vitest does the same by default, but you can override snapshotOptions.snapshotsDirName in vitest.config.ts to consolidate snapshots elsewhere.
Concurrent tests. Vitest runs tests concurrently within a file by default when you use test.concurrent. Jest does not. Snapshot writes are serialized safely in Vitest even in concurrent mode, but if two concurrent tests try to update the same named snapshot you'll get a conflict warning.
toMatchFileSnapshot. Vitest adds this API (not in Jest) for asserting against an arbitrary file on disk rather than the auto-generated .snap file:
import { expect, it } from 'vitest'
it('renders expected HTML', async () => {
const html = await renderPage('/about')
await expect(html).toMatchFileSnapshot('./snapshots/about.html')
})The file is created on first run and compared on subsequent runs. This is useful for larger outputs (full HTML pages, generated SQL, JSON configs) where a .snap file feels too implicit.
Snapshot serializers. Both frameworks support custom serializers, but Vitest exposes expect.addSnapshotSerializer globally and also accepts a snapshotSerializers array in vitest.config.ts. The config-level approach means you can apply serializers project-wide without importing them in every test file.
The --update flag. Jest uses --updateSnapshot (or -u). Vitest uses --update-snapshots (or -u). Same semantics, different flag name.
Basic Snapshot Usage
import { describe, expect, it } from 'vitest'
import { formatUser } from './formatUser'
describe('formatUser', () => {
it('formats a complete user object', () => {
const user = {
id: 1,
name: 'Alice',
role: 'admin',
createdAt: new Date('2024-01-15'),
}
expect(formatUser(user)).toMatchSnapshot()
})
})First run creates __snapshots__/formatUser.test.ts.snap:
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`formatUser formats a complete user object 1`] = `
{
"displayName": "Alice",
"isAdmin": true,
"joinedYear": 2024,
}
`;The snapshot key is derived from the full test name. If you rename the test, Vitest treats the old snapshot as obsolete and the new one as new. Run with --update-snapshots to clean up obsolete snapshots and write new ones.
Named snapshots. You can pass a hint string to distinguish multiple snapshots in one test:
it('formats users in both roles', () => {
expect(formatUser(adminUser)).toMatchSnapshot('admin')
expect(formatUser(viewerUser)).toMatchSnapshot('viewer')
})Inline Snapshots
Inline snapshots store the expected value directly in the test file rather than in a separate .snap file. They're ideal for small outputs where keeping the expected value next to the assertion makes the test easier to read.
it('generates a slug', () => {
expect(slugify('Hello World')).toMatchInlineSnapshot(`"hello-world"`)
})The first time Vitest encounters a toMatchInlineSnapshot() call with no argument (or an empty string), it writes the serialized value directly into the source file. From then on, the test file itself serves as both the test and the snapshot record.
// Write this initially:
it('formats price', () => {
expect(formatPrice(1999, 'USD')).toMatchInlineSnapshot()
})
// After first run, Vitest rewrites the file to:
it('formats price', () => {
expect(formatPrice(1999, 'USD')).toMatchInlineSnapshot(`"$19.99"`)
})Inline snapshots are best for outputs under ~10 lines. For larger objects, .snap files keep tests readable. The rule of thumb: if reading the inline snapshot tells you something meaningful about what the function does, use it. If it's a wall of JSON, use a named file snapshot or toMatchFileSnapshot.
Custom Serializers
The default Vitest serializer handles plain objects, arrays, strings, numbers, and DOM nodes (via @testing-library integration). For anything else — styled-components, CSS modules, custom class instances — you need a custom serializer.
Registering a serializer globally via config:
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
snapshotSerializers: ['./src/test/serializers/styled-components.ts'],
},
})Writing a serializer for styled-components:
// src/test/serializers/styled-components.ts
import { ComponentType } from 'react'
export default {
test(val: unknown): boolean {
return (
val != null &&
typeof val === 'object' &&
'displayName' in val &&
typeof (val as any).styledComponentId === 'string'
)
},
print(val: unknown, serialize: (val: unknown) => string): string {
const component = val as ComponentType & {
displayName: string
styledComponentId: string
}
return `Styled(${component.displayName ?? 'Unknown'}) [${component.styledComponentId}]`
},
}Registering a serializer per-file:
import { expect } from 'vitest'
expect.addSnapshotSerializer({
test: (val) => val instanceof Map,
print: (val, serialize) => {
const map = val as Map<unknown, unknown>
const entries = [...map.entries()].map(
([k, v]) => ` ${serialize(k)} => ${serialize(v)}`
)
return `Map {\n${entries.join(',\n')}\n}`
},
})Serializer for CSS-in-JS (Emotion/vanilla-extract):
expect.addSnapshotSerializer({
test: (val) =>
typeof val === 'string' && /^css-[a-z0-9]+$/.test(val),
print: (val) => `"[css-hash]"`,
})This replaces non-deterministic CSS class hashes with a stable placeholder, preventing snapshots from failing on every build due to hash changes.
React Component Snapshot Testing
Use @testing-library/react with Vitest. The render function returns a container you can snapshot directly, or use asFragment() for a clean DocumentFragment:
import { render } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { UserCard } from './UserCard'
describe('UserCard', () => {
it('renders a verified user', () => {
const { asFragment } = render(
<UserCard
name="Alice"
role="admin"
verified={true}
avatarUrl="https://example.com/alice.jpg"
/>
)
expect(asFragment()).toMatchSnapshot()
})
it('renders an unverified user with prompt', () => {
const { asFragment } = render(
<UserCard name="Bob" role="viewer" verified={false} />
)
expect(asFragment()).toMatchInlineSnapshot(`
<DocumentFragment>
<div class="user-card">
<span class="name">Bob</span>
<span class="role">viewer</span>
<span class="unverified-badge">Verify your account</span>
</div>
</DocumentFragment>
`)
})
})Pitfall: dynamic content. Timestamps, random IDs, and animation states will make snapshots flaky. Mock them before snapshotting:
it('renders with stable timestamp', () => {
vi.setSystemTime(new Date('2024-06-01T12:00:00Z'))
const { asFragment } = render(<ActivityFeed userId="u1" />)
expect(asFragment()).toMatchSnapshot()
vi.useRealTimers()
})For components that generate random keys or IDs, mock the ID generator:
vi.mock('./utils/id', () => ({ generateId: () => 'test-id-stable' }))Snapshot depth. Snapshotting a full page component produces a massive .snap file that breaks on any style or markup change anywhere in the tree. Prefer snapshotting at the unit level — individual components with controlled props — not full page renders. Reserve full-tree snapshots for truly stable layout components.
Snapshot Testing with Vue
The setup with Vue is nearly identical. Use @testing-library/vue or @vue/test-utils:
import { mount } from '@vue/test-utils'
import { describe, expect, it } from 'vitest'
import StatusBadge from './StatusBadge.vue'
describe('StatusBadge', () => {
it('renders active state', () => {
const wrapper = mount(StatusBadge, {
props: { status: 'active', label: 'Live' },
})
expect(wrapper.html()).toMatchSnapshot()
})
it('renders error state inline', () => {
const wrapper = mount(StatusBadge, {
props: { status: 'error', label: 'Failed' },
})
expect(wrapper.html()).toMatchInlineSnapshot(`
"<div class="badge badge--error">
<span>Failed</span>
</div>"
`)
})
})With @testing-library/vue, use render and asFragment() the same way as React:
import { render } from '@testing-library/vue'
import { expect, it } from 'vitest'
import Dropdown from './Dropdown.vue'
it('renders dropdown options', () => {
const { asFragment } = render(Dropdown, {
props: {
options: ['Apple', 'Banana', 'Cherry'],
placeholder: 'Select a fruit',
},
})
expect(asFragment()).toMatchSnapshot()
})Managing Snapshot Files
Snapshot files are generated artifacts but they should be committed to version control. This is intentional — the .snap files ARE the expected output. A diff in a .snap file during code review tells reviewers exactly what changed in the rendered output.
Naming discipline. Snapshot keys are auto-generated from test names. Descriptive test names produce readable snapshot keys. Vague names like it('works') produce useless keys like works 1. Write test names that describe the scenario: renders admin badge when role is admin.
Orphan snapshots. When you rename or delete a test, its snapshot key becomes orphaned. Vitest reports these as "obsolete snapshots" at the end of a test run. Clean them with:
npx vitest run --update-snapshotsThis updates changed snapshots AND removes obsolete ones. Do not use this as a shortcut to silence failing tests.
Snapshot file organization. By default, each test file gets one .snap file in an adjacent __snapshots__ directory. For large projects, consider using snapshotsDirName to centralize snapshots:
// vitest.config.ts
export default defineConfig({
test: {
snapshotOptions: {
snapshotsDirName: '__snapshots__',
},
},
})The --update Flag and When to Use It
npx vitest run --update-snapshots (shorthand: -u) updates all failing snapshots to match the current output. This is correct behavior when:
- You intentionally changed the component's markup or output
- You're updating a custom serializer that changes how values are printed
- You've resolved a flakiness issue (e.g., replaced a dynamic timestamp with a mock) and need to re-record
It is not correct when:
- CI is failing and you don't know why — investigate the diff first
- A refactor "shouldn't have changed anything" — if the snapshot changed, something changed; find out what
- You're updating snapshots you haven't reviewed — always read the diff before updating
The workflow for an intentional snapshot update:
- Make the code change
- Run
vitest run— observe which snapshots fail and read the diffs - If the diffs match your intent, run
vitest run --update-snapshots - Commit both the code change and the updated
.snapfiles together - In the PR description, explicitly note that snapshots were updated and why
CI Discipline for Snapshots
Never run --update-snapshots in CI. CI should only run vitest run (no update flag). If a snapshot fails in CI, that is a signal, not a nuisance. Treat it like any other test failure: understand the diff, update locally with intent, commit the result.
Snapshot diffs in PR reviews. Configure your CI to show snapshot diffs as part of the test failure output. Vitest's default output already includes the diff inline in the terminal. If you're aggregating test results, make sure the snapshot diff is preserved — it's often the most useful signal in a failing test.
Preventing accidental snapshot updates. Add a CI check that fails if there are uncommitted changes after vitest run:
# .github/workflows/test.yml
- name: Run tests
run: npx vitest run
- name: Check for uncommitted snapshot changes
run: |
if [ -n "$(git status --porcelain '**/*.snap')" ]; then
echo "Snapshot files were modified during test run. Run tests locally and commit the updated snapshots."
git diff '**/*.snap'
exit 1
fiThis catches the case where a developer forgets to commit updated snapshots after running --update-snapshots locally.
Don't snapshot everything. The CI snapshot burden grows with every snapshot you add. Ask before adding a new snapshot test: would a unit assertion (expect(user.role).toBe('admin')) be more precise? Snapshots are good for catching unexpected structural changes. They're poor substitutes for explicit assertions about values you actually care about.
Vitest UI Snapshot Review
Vitest ships a browser-based UI (npx vitest --ui) that includes a snapshot viewer. When a snapshot test fails, the UI shows a side-by-side diff of the expected and received values. For component snapshots, it renders the HTML diff with highlighted insertions and deletions.
You can approve snapshot updates directly from the UI without re-running the test suite from the terminal. Click the "Update" button next to a failing snapshot to write the new value. This is useful during active development when you're iterating on a component and expect multiple rounds of snapshot updates.
The UI also lists all snapshots by test file, showing which are passing, failing, or obsolete. Obsolete snapshots are displayed with a delete option — use this to clean up after renaming or removing tests.
Key Takeaways
- Vitest snapshots are API-compatible with Jest. Migration is usually zero-effort. Key differences:
toMatchFileSnapshot(Vitest only),snapshotSerializersin config (Vitest),--update-snapshotsflag name. - Inline snapshots belong next to small, readable outputs. If the inline value is longer than the test itself, use a
.snapfile instead. - Custom serializers solve the non-determinism problem. CSS hashes, random IDs, and timestamps all need serializers or mocks before you can snapshot them reliably.
- Component snapshots should be narrow. Snapshot individual components with controlled props, not full page renders. Wide snapshots break constantly and the diffs are too large to review.
- Commit
.snapfiles. They are the expected output. Snapshot diffs in PR review are valuable signal about what changed in rendered markup. --update-snapshotsis not a fix. It's a deliberate action you take after reviewing the diff and confirming the change is correct. Never run it in CI. Never run it to silence failures you haven't read.- The Vitest UI snapshot viewer speeds up iteration. Use
vitest --uiduring active component development to review and approve snapshot changes without leaving the browser.