Skip to main content
Snapshot testing saves the output of a value and compares it against future test runs. Use it for UI components, complex objects, or any output that needs to remain consistent.

Basic Snapshots

Snapshot tests are written using the .toMatchSnapshot() matcher:
test.ts
The first time this test runs, Bun serializes the argument to expect and writes it to a snapshot file in a __snapshots__ directory alongside the test file.

Snapshot Files

After the first run, Bun creates:
directory structure
The snapshot file contains:
__snapshots__/snap.test.ts.snap
On future runs, Bun compares the argument against the snapshot on disk.

Updating Snapshots

Regenerate snapshots with:
terminal
Do this when you’ve intentionally changed the output or added new snapshot tests.

Inline Snapshots

For smaller values, use .toMatchInlineSnapshot(). Inline snapshots are stored directly in your test file:
test.ts
After the first run, Bun automatically updates your test file:
test.ts

Using Inline Snapshots

  1. Write your test with .toMatchInlineSnapshot()
  2. Run the test once
  3. Bun automatically updates your test file with the snapshot
  4. On subsequent runs, Bun compares the value against the inline snapshot

Error Snapshots

You can also snapshot error messages with .toThrowErrorMatchingSnapshot() and .toThrowErrorMatchingInlineSnapshot():
test.ts
After running, the inline version becomes:
test.ts

Advanced Snapshot Usage

Complex Objects

Snapshots work well with complex nested objects:
test.ts

Array Snapshots

Arrays are also well-suited for snapshot testing:
test.ts

Function Output Snapshots

Snapshot the output of functions:
test.ts

React Component Snapshots

Snapshots work well for React components:
test.ts

Property Matchers

For values that change between test runs (like timestamps or IDs), use property matchers:
test.ts
The snapshot file stores:
snapshot file

Best Practices

Keep Snapshots Small

test.ts

Use Descriptive Test Names

test.ts
test.ts

Handle Dynamic Data

test.ts

Managing Snapshots

Reviewing Snapshot Changes

When snapshots change, carefully review them:
terminal

Organizing Large Snapshot Files

For large projects, consider organizing tests to keep snapshot files manageable:
directory structure

Troubleshooting

Snapshot Failures

When snapshots fail, you’ll see a diff:
diff
Common causes:
  • Intentional changes (update with --update-snapshots)
  • Unintentional changes (fix the code)
  • Dynamic data (use property matchers)
  • Environment differences (normalize the data)

Platform Differences

Be aware of platform-specific differences:
test.ts