Overview
Snapshot testing captures the rendered output of a component and saves it as a reference. Future test runs compare the current output against the saved snapshot, detecting any unexpected changes. This is particularly useful for catching unintended UI regressions.How Snapshot Testing Works
- First Run: Vitest renders your component and saves the output to a
__snapshots__directory - Subsequent Runs: Vitest compares new renders against the saved snapshot
- On Changes: If output differs, the test fails and shows you the difference
- Update Snapshots: If changes are intentional, update the snapshot
Creating Snapshot Tests
Here’s a real example from the codebase:MyAwesomeApp.test.tsx
Snapshot Methods
Generated Snapshot Files
When you run snapshot tests, Vitest creates a__snapshots__ directory containing .snap files:
MyAwesomeApp.test.tsx.snap
Snapshot files should be committed to version control. They serve as documentation of your component’s output and allow reviewers to see UI changes in pull requests.
Updating Snapshots
When you intentionally change a component’s output, snapshots need updating:When to Update Snapshots
- You intentionally changed the component’s UI
- You added or removed elements
- You updated text content, styles, or attributes
- A dependency update changed rendering output
Always review snapshot diffs carefully before updating. Unexpected changes might indicate bugs rather than intended modifications.
Snapshot Testing Best Practices
1. Keep Snapshots Small and Focused
2. Combine with Specific Assertions
3. Use Descriptive Test Names
Snapshot file exports use your test names, so make them clear:When to Use Snapshot Testing
Good Use Cases:- Testing component structure and layout
- Catching unintended CSS or style changes
- Verifying consistent rendering across refactors
- Testing configuration objects or data structures
- Components with dynamic data (timestamps, random IDs)
- Large components (breaks are hard to review)
- Testing logic or behavior (use specific assertions instead)
Snapshot testing complements but doesn’t replace traditional assertions. Use both for comprehensive test coverage: snapshots for structure, assertions for specific behavior.
Troubleshooting
Snapshot Mismatches
When a snapshot test fails:- Review the diff: Vitest shows what changed
- Check if intentional: Did you mean to change the output?
- Update if correct: Run
npm test -- -uto update - Fix bug if incorrect: Revert your code changes
Dynamic Content
For components with timestamps or random values:Running Snapshot Tests
Next Steps
- Review snapshot diffs in pull requests
- Set up CI/CD to catch snapshot failures
- Learn about inline snapshots with
toMatchInlineSnapshot() - Explore custom snapshot serializers for cleaner output