Jest Inline Snapshots: A Practical Guide
Jest has two kinds of snapshot tests: external snapshots (stored in __snapshots__/ files) and inline snapshots (written directly in the test file). Inline snapshots were added in Jest 26 and offer a different trade-off that makes them preferable in many situations.
This guide covers how inline snapshots work, how they compare to external snapshots, and when to use each.
What Are Inline Snapshots?
An inline snapshot is a snapshot stored in the test source file itself, inside the test assertion:
// External snapshot
test('renders user card', () => {
const tree = render(<UserCard name="Alice" />)
expect(tree).toMatchSnapshot() // stored in __snapshots__/UserCard.test.js.snap
})
// Inline snapshot
test('renders user card', () => {
const tree = render(<UserCard name="Alice" />)
expect(tree).toMatchInlineSnapshot(`
<div class="user-card">
<h2>Alice</h2>
</div>
`)
})With inline snapshots, you see the expected output directly in the test. With external snapshots, you have to open a separate .snap file.
How Inline Snapshots Work
When you first write a test with toMatchInlineSnapshot() and leave the template literal empty:
expect(output).toMatchInlineSnapshot()Jest runs the test, captures the output, and writes the snapshot directly into your source file. After the first run, the test looks like:
expect(output).toMatchInlineSnapshot(`
"Hello, Alice!"
`)On subsequent runs, Jest compares the current output against the inline string. If they don't match, the test fails.
To update an inline snapshot after an intentional change:
npx jest --updateSnapshot
# or
npx jest -uJest rewrites the inline string in your source file.
Inline vs External Snapshots
| Inline | External | |
|---|---|---|
| Location | In the test file | In __snapshots__/ directory |
| Readability | See expected output without leaving the test | Requires opening a separate file |
| PR diffs | Snapshot change visible in test file diff | Separate .snap file diff |
| Large outputs | Clutters test file | Contained in snapshot file |
| Multiple snapshots per test | Becomes unwieldy | Natural |
Use inline snapshots when:
- The snapshot is small (a few lines)
- You want reviewers to see the expected output alongside the test
- You're testing a function's return value, not a full component tree
Use external snapshots when:
- The snapshot is large (full component renders)
- A single test has many snapshot assertions
- The snapshot output is too verbose to be readable inline
Practical Examples
Serialized Data
test('formats user for API response', () => {
const user = new User({ id: 1, name: 'Alice', email: 'alice@example.com' })
expect(user.toJSON()).toMatchInlineSnapshot(`
{
"email": "alice@example.com",
"id": 1,
"name": "Alice",
}
`)
})The snapshot is small enough that it's readable inline.
Error Messages
test('throws on invalid input', () => {
expect(() => parseConfig({ timeout: -1 })).toThrowErrorMatchingInlineSnapshot(`
"timeout must be a positive number, got -1"
`)
})Error message snapshots are ideal for inline — you see the expected error in the test itself.
SQL Queries
Testing that a function generates the correct SQL:
test('generates correct query for date range', () => {
const query = buildQuery({ startDate: '2024-01-01', endDate: '2024-12-31' })
expect(query).toMatchInlineSnapshot(`
"SELECT * FROM orders
WHERE created_at >= '2024-01-01'
AND created_at <= '2024-12-31'
ORDER BY created_at DESC"
`)
})CLI Output
test('formats help output', () => {
const output = cli.help()
expect(output).toMatchInlineSnapshot(`
"Usage: mycli [options] <command>
Commands:
init Initialize a new project
build Build the project
deploy Deploy to production
Options:
--verbose Enable verbose output
--help Show this help"
`)
})When Inline Becomes External
Inline snapshots have a size limit — very large snapshots make test files hard to read. The rule of thumb: if the snapshot is longer than the test itself, use an external snapshot.
// This is too long to be inline — use toMatchSnapshot() instead
test('full component render', () => {
const { container } = render(<FullPageLayout />)
expect(container).toMatchSnapshot() // external
})Updating Inline Snapshots
# Update all snapshots (inline and external)
npx jest --updateSnapshot
# Update snapshots for a specific test file
npx jest --updateSnapshot UserCard.test.js
# Update snapshots interactively (press u in watch mode)
npx jest --watchWhen you run --updateSnapshot, Jest rewrites the inline strings in your test files. Commit the changes to update the baseline.
Never update snapshots without reviewing the diff. Updating is easy — reviewing what changed is the important part.
Prettier Integration
If your project uses Prettier, inline snapshots are formatted consistently. Configure Jest to use your Prettier config:
// jest.config.js
module.exports = {
snapshotFormat: {
indent: 2,
printBasicPrototype: false
}
}Or install jest-snapshot-serializer-raw for custom formatting.
Custom Serializers with Inline Snapshots
Custom serializers work with inline snapshots:
// Serialize only specific properties
expect.addSnapshotSerializer({
test: (val) => val instanceof User,
print: (val) => `User { id: ${val.id}, name: "${val.name}" }`
})
test('serializes user', () => {
const user = new User({ id: 1, name: 'Alice', createdAt: new Date() })
expect(user).toMatchInlineSnapshot(`User { id: 1, name: "Alice" }`)
// createdAt is excluded by the serializer — no timestamp flakiness
})This is particularly useful when you want to snapshot an object but exclude dynamic fields (timestamps, IDs generated at runtime).
Property Matchers with Inline Snapshots
Use expect.any() matchers for dynamic values that you still want to include in the snapshot:
test('creates order with correct structure', () => {
const order = createOrder({ items: ['apple', 'banana'], userId: 42 })
expect(order).toMatchInlineSnapshot(
{
id: expect.any(String), // UUID, don't snapshot exact value
createdAt: expect.any(Date) // dynamic timestamp
},
`
{
"createdAt": Any<Date>,
"id": Any<String>,
"items": [
"apple",
"banana",
],
"userId": 42,
}
`
)
})The property matchers tell Jest which fields to match by type rather than exact value, preventing flakiness from dynamic data.
Summary
Inline snapshots are the better choice when the snapshot is small enough to read in context. They keep expected output visible in the test, make PR diffs more meaningful, and reduce the cognitive load of maintaining a separate .snap file.
Use external snapshots for large outputs or tests with many snapshots. Use inline snapshots for short outputs — error messages, serialized values, generated queries — where seeing the expected result next to the test adds clarity.