Basic Snapshots
Snapshot tests are written using the.toMatchSnapshot() matcher:
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:
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():
Advanced Snapshot Usage
Complex Objects
Snapshots work well with complex nested objects:Array Snapshots
Arrays are also well-suited for snapshot testing:Function Output Snapshots
Snapshot the output of functions:React Component Snapshots
Snapshots work well for React components:Property Matchers
For values that change between test runs (like timestamps or IDs), use property matchers:snapshot file
Best Practices
Keep Snapshots Small
Use Descriptive Test Names
Group Related Snapshots
Handle Dynamic Data
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)