Basic snapshots
Use.toMatchSnapshot() to capture a value:
Snapshot file location
Snapshots are stored in a__snapshots__ directory alongside the test file:
__snapshots__/user.test.ts.snap
Updating snapshots
When output intentionally changes, regenerate snapshots with: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.
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: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:| Cause | Solution |
|---|---|
| Intentional change | Run bun test --update-snapshots |
| Unintentional regression | Fix the code that produces the output |
| Dynamic data in snapshot | Use property matchers for volatile fields |
| Platform-specific formatting | Normalize values (e.g., path separators) before snapshotting |
Best practices
Keep snapshots small and focused
Keep snapshots small and focused
Snapshot only the part of the output that matters to the test. Large snapshots are hard to review when they change.
Handle dynamic data with property matchers
Handle dynamic data with property matchers
Review snapshot changes carefully
Review snapshot changes carefully
Snapshot diffs in pull requests deserve the same scrutiny as code changes. An unexpected snapshot change is often a sign of a bug.
Group snapshots with describe
Group snapshots with describe
Organizing snapshots inside
describe blocks makes the snapshot file easier to navigate: