Basic Snapshots
Snapshot tests are written using the.toMatchSnapshot() matcher:
expect will be serialized and written to a special snapshot file in a __snapshots__ directory alongside the test file.
Snapshot Files
After running the test above, Bun will create:directory structure
snapshot file
Updating Snapshots
Snapshots can be re-generated with the following command:terminal
- You’ve intentionally changed the output
- You’re adding new snapshot tests
- The expected output has legitimately changed
Inline Snapshots
For smaller values, you can use inline snapshots with.toMatchInlineSnapshot(). These 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, the value will be compared against the inline snapshot
Error Snapshots
You can also snapshot error messages using.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 are particularly useful for React components:Property Matchers
For values that change between test runs (like timestamps or IDs), use property matchers:snapshot file
Custom Serializers
You can customize how objects are serialized in snapshots: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
Cleaning Up Unused Snapshots
Bun will warn about unused snapshots:warning
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)