Snapshot
Learn Snapshot by video from Vue SchoolSnapshot tests are a very useful tool whenever you want to make sure the output of your functions does not change unexpectedly.
When using snapshot, Vitest will take a snapshot of the given value, then compare it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new version of the result.
Use Snapshots
To snapshot a value, you can use the toMatchSnapshot() from expect() API:
import { expect, it } from 'vitest'
it('toUpperCase', () => {
const result = toUpperCase('foobar')
expect(result).toMatchSnapshot()
})The first time this test is run, Vitest creates a snapshot file that looks like this:
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports['toUpperCase 1'] = '"FOOBAR"'The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. On subsequent test runs, Vitest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code that should be fixed, or the implementation has changed and the snapshot needs to be updated.
WARNING
When using Snapshots with async concurrent tests, expect from the local Test Context must be used to ensure the right test is detected.
Inline Snapshots
Similarly, you can use the toMatchInlineSnapshot() to store the snapshot inline within the test file.
import { expect, it } from 'vitest'
it('toUpperCase', () => {
const result = toUpperCase('foobar')
expect(result).toMatchInlineSnapshot()
})Instead of creating a snapshot file, Vitest will modify the test file directly to update the snapshot as a string:
import { expect, it } from 'vitest'
it('toUpperCase', () => {
const result = toUpperCase('foobar')
expect(result).toMatchInlineSnapshot('"FOOBAR"')
})This allows you to see the expected output directly without jumping across different files.
WARNING
When using Snapshots with async concurrent tests, expect from the local Test Context must be used to ensure the right test is detected.
Updating Snapshots
When the received value doesn't match the snapshot, the test fails and shows you the difference between them. When the snapshot change is expected, you may want to update the snapshot from the current state.
In watch mode, you can press the u key in the terminal to update the failed snapshot directly.
Or you can use the --update or -u flag in the CLI to make Vitest update snapshots.
vitest -uCI behavior
By default, Vitest does not write snapshots in CI (process.env.CI is truthy) and any snapshot mismatches, missing snapshots, and obsolete snapshots fail the run. See update for the details.
An obsolete snapshot is a snapshot entry (or snapshot file) that no longer matches any collected test. This usually happens after removing or renaming tests.
File Snapshots
When calling toMatchSnapshot(), we store all snapshots in a formatted snap file. That means we need to escape some characters (namely the double-quote " and backtick `) in the snapshot string. Meanwhile, you might lose the syntax highlighting for the snapshot content (if they are in some language).
In light of this, we introduced toMatchFileSnapshot() to explicitly match against a file. This allows you to assign any file extension to the snapshot file, and makes them more readable.
import { expect, it } from 'vitest'
it('render basic', async () => {
const result = renderHTML(h('div', { class: 'foo' }))
await expect(result).toMatchFileSnapshot('./test/basic.output.html')
})It will compare with the content of ./test/basic.output.html. And can be written back with the --update flag.
Visual Snapshots
For visual regression testing of UI components and pages, Vitest provides built-in support through browser mode with the toMatchScreenshot() assertion:
import { expect, test } from 'vitest'
import { page } from 'vitest/browser'
test('button looks correct', async () => {
const button = page.getByRole('button')
await expect(button).toMatchScreenshot('primary-button')
})This captures screenshots and compares them against reference images to detect unintended visual changes. Learn more in the Visual Regression Testing guide.
Aria Snapshots
Aria snapshots capture the accessibility tree of a DOM element and compare it against a stored template. Inspired by Playwright's aria snapshots, they provide a semantic alternative to visual regression testing — asserting structure and meaning rather than pixels.
For example, given this HTML:
<body>
<h1>Welcome</h1>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</body>You can assert its accessibility tree:
import { expect, test } from 'vitest'
import { page } from 'vitest/browser'
test('navigation structure', async () => {
await expect.element(page.getByRole('navigation')).toMatchAriaInlineSnapshot(`
- heading "Welcome" [level=1]
- navigation:
- link "Home":
- /url: /
- link "About":
- /url: /about
`)
})See the dedicated ARIA Snapshots guide for syntax details, retry behavior in Browser Mode, and file vs. inline snapshot examples. See toMatchAriaSnapshot and toMatchAriaInlineSnapshot for the full API reference.
Custom Serializer
You can add your own logic to alter how your snapshots are serialized. Like Jest, Vitest has default serializers for built-in JavaScript types, HTML elements, ImmutableJS and for React elements.
You can explicitly add custom serializer by using expect.addSnapshotSerializer API.
expect.addSnapshotSerializer({
serialize(val, config, indentation, depth, refs, printer) {
// `printer` is a function that serializes a value using existing plugins.
return `Pretty foo: ${printer(
val.foo,
config,
indentation,
depth,
refs,
)}`
},
test(val) {
return val && Object.prototype.hasOwnProperty.call(val, 'foo')
},
})We also support snapshotSerializers option to implicitly add custom serializers.
import { SnapshotSerializer } from 'vitest'
export default {
serialize(val, config, indentation, depth, refs, printer) {
// `printer` is a function that serializes a value using existing plugins.
return `Pretty foo: ${printer(
val.foo,
config,
indentation,
depth,
refs,
)}`
},
test(val) {
return val && Object.prototype.hasOwnProperty.call(val, 'foo')
},
} satisfies SnapshotSerializerimport { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
snapshotSerializers: ['path/to/custom-serializer.ts'],
},
})After adding a test like this:
test('foo snapshot test', () => {
const bar = {
foo: {
x: 1,
y: 2,
},
}
expect(bar).toMatchSnapshot()
})You will get the following snapshot:
Pretty foo: Object {
"x": 1,
"y": 2,
}We are using Jest's pretty-format for serializing snapshots. You can read more about it here: pretty-format.
Custom Snapshot Domain experimental
Custom serializers control how values are rendered into snapshot strings, but comparison is still string equality. A domain snapshot adapter goes further — it owns the entire comparison pipeline: how to capture a value, render it, parse a stored snapshot, and match them semantically.
This is useful when snapshot comparison needs to be smarter than ===. For example, the built-in aria snapshots use a domain adapter to support regex patterns and preserve hand-edited patterns when running with --update — the adapter's match method can return a mergedExpected string so only the changed literal parts are overwritten.
The adapter interface
A domain adapter implements four methods:
import type { DomainSnapshotAdapter } from '@vitest/snapshot'
const myAdapter: DomainSnapshotAdapter<Captured, Expected> = {
name: 'my-domain',
// Extract structured data from the received value
capture(received) { /* ... */ },
// Render captured data as the snapshot string (what gets stored)
render(captured) { /* ... */ },
// Parse a stored snapshot string into a structured expected value
parseExpected(input) { /* ... */ },
// Compare captured vs expected, return pass/fail and diff info
match(captured, expected) { /* ... */ },
}Registration
Register an adapter in your test setup file:
import { expect } from 'vitest'
expect.addSnapshotDomain(myAdapter)Then use it in tests via toMatchDomainSnapshot or toMatchDomainInlineSnapshot:
expect(value).toMatchDomainSnapshot('my-domain')
expect(value).toMatchDomainInlineSnapshot(`key=value`, 'my-domain')Example: key-value adapter
A minimal adapter that stores objects as key=value lines, with regex pattern support (full source):
import type {
DomainMatchResult,
DomainSnapshotAdapter,
} from '@vitest/snapshot'
interface KVCaptured {
entries: { key: string; value: string }[]
}
interface KVExpected {
entries: { key: string; value: string | RegExp }[]
}
export const kvAdapter: DomainSnapshotAdapter<KVCaptured, KVExpected> = {
name: 'kv',
capture(received) {
const entries = Object.entries(received as Record<string, string>)
.map(([key, value]) => ({ key, value: String(value) }))
return { entries }
},
render(captured) {
return captured.entries.map(e => `${e.key}=${e.value}`).join('\n')
},
parseExpected(input) {
const entries = input.trim().split('\n').map((line) => {
const eq = line.indexOf('=')
const key = line.slice(0, eq)
const raw = line.slice(eq + 1)
const value = (raw.startsWith('/') && raw.endsWith('/'))
? new RegExp(raw.slice(1, -1))
: raw
return { key, value }
})
return { entries }
},
match(captured, expected): DomainMatchResult {
let allPass = true
for (let i = 0; i < captured.entries.length; i++) {
const cap = captured.entries[i]
const exp = expected.entries[i]
if (!exp) {
allPass = false
}
else if (exp.value instanceof RegExp) {
if (!exp.value.test(cap.value)) allPass = false
}
else if (cap.value !== exp.value) {
allPass = false
}
}
return {
pass: allPass,
// Optionally return mergedExpected, actual, expected for diffs
// and pattern-preserving updates
// actual: "...",
// expected: "...",
// mergedExpected: "...",
}
},
}import { expect } from 'vitest'
import { kvAdapter } from './kv-adapter'
expect.addSnapshotDomain(kvAdapter)import { expect, test } from 'vitest'
test('user data', () => {
const user = { name: 'Alice', score: '42' }
expect(user).toMatchDomainSnapshot('kv')
})
test('user data inline', () => {
const user = { name: 'Alice', score: '42' }
expect(user).toMatchDomainInlineSnapshot(`
name=Alice
score=/\\d+/
`, 'kv')
})Difference from Jest
Vitest provides an almost compatible Snapshot feature with Jest's with a few exceptions:
1. Comment header in the snapshot file is different
- // Jest Snapshot v1, https://goo.gl/fbAQLP
+ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.htmlThis does not really affect the functionality but might affect your commit diff when migrating from Jest.
2. printBasicPrototype is default to false
Both Jest and Vitest's snapshots are powered by pretty-format. In Vitest we set printBasicPrototype default to false to provide a cleaner snapshot output, while in Jest <29.0.0 it's true by default.
import { expect, test } from 'vitest'
test('snapshot', () => {
const bar = [
{
foo: 'bar',
},
]
// in Jest
expect(bar).toMatchInlineSnapshot(`
Array [
Object {
"foo": "bar",
},
]
`)
// in Vitest
expect(bar).toMatchInlineSnapshot(`
[
{
"foo": "bar",
},
]
`)
})We believe this is a more reasonable default for readability and overall DX. If you still prefer Jest's behavior, you can change your config:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
snapshotFormat: {
printBasicPrototype: true,
},
},
})3. Chevron > is used as a separator instead of colon : for custom messages
Vitest uses chevron > as a separator instead of colon : for readability, when a custom message is passed during creation of a snapshot file.
For the following example test code:
test('toThrowErrorMatchingSnapshot', () => {
expect(() => {
throw new Error('error')
}).toThrowErrorMatchingSnapshot('hint')
})In Jest, the snapshot will be:
exports[`toThrowErrorMatchingSnapshot: hint 1`] = `"error"`;In Vitest, the equivalent snapshot will be:
exports[`toThrowErrorMatchingSnapshot > hint 1`] = `[Error: error]`;4. default Error snapshot is different for toThrowErrorMatchingSnapshot and toThrowErrorMatchingInlineSnapshot
import { expect, test } from 'vitest'
test('snapshot', () => {
// in Jest and Vitest
expect(new Error('error')).toMatchInlineSnapshot(`[Error: error]`)
// Jest snapshots `Error.message` for `Error` instance
// Vitest prints the same value as toMatchInlineSnapshot
expect(() => {
throw new Error('error')
}).toThrowErrorMatchingInlineSnapshot(`"error"`)
}).toThrowErrorMatchingInlineSnapshot(`[Error: error]`)
})