Basic Snapshots
Snapshot tests are written using the.toMatchSnapshot() matcher:
test.ts
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
__snapshots__/snap.test.ts.snap
Updating Snapshots
Regenerate snapshots with:terminal
Inline Snapshots
For smaller values, use.toMatchInlineSnapshot(). Inline snapshots are stored directly in your test file:
test.ts
test.ts
Using Inline Snapshots
- Write your test with
.toMatchInlineSnapshot() - Run the test once
- Bun automatically updates your test file with the snapshot
- 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
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
snapshot file
Best Practices
Keep Snapshots Small
test.ts
Use Descriptive Test Names
test.ts
Group Related Snapshots
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
- 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