Skip to main content
Snapshot testing saves the serialized output of a value and compares it on future runs. This is useful for complex objects, component output, or any value that should remain stable over time.

Basic snapshots

Use .toMatchSnapshot() to capture a value:
On the first run, the value is serialized and written to a snapshot file. On subsequent runs, the value is compared against the stored snapshot — the test fails if they differ.

Snapshot file location

Snapshots are stored in a __snapshots__ directory alongside the test file:
The snapshot file contents look like:
__snapshots__/user.test.ts.snap

Updating snapshots

When output intentionally changes, regenerate snapshots with:
After updating, commit the snapshot files alongside your code changes so they are reviewed as part of the diff.

Inline snapshots

For small values, use .toMatchInlineSnapshot() to store the snapshot directly in the test file. On the first run, Bun writes the value into your test file automatically.
After the first run, your test file is updated with the snapshot value filled in. Subsequent runs compare against the inline string.

Error snapshots

Capture and compare error messages with .toThrowErrorMatchingSnapshot() and .toThrowErrorMatchingInlineSnapshot():

Advanced usage

Complex objects

Snapshots are particularly effective for deeply nested structures:

Property matchers

For values that change between runs (timestamps, random IDs), use property matchers to assert the shape while ignoring volatile values:
The snapshot stores Any<String> for the matched fields while capturing the exact value of name.

React component snapshots

Snapshots work well for testing rendered HTML output:

Custom serializers

Register a custom serializer to control how a type is printed in snapshots:

Troubleshooting snapshot failures

When a snapshot test fails, Bun shows a diff:
Common causes:

Best practices

Snapshot only the part of the output that matters to the test. Large snapshots are hard to review when they change.
Snapshot diffs in pull requests deserve the same scrutiny as code changes. An unexpected snapshot change is often a sign of a bug.
Organizing snapshots inside describe blocks makes the snapshot file easier to navigate: