Jest's Snapshot Testing is a powerful tool for ensuring UI components or data structures don't change unexpectedly:
Snapshot Testing Principles:
- On first run, Jest captures component output and saves it as a snapshot file
- On subsequent runs, it compares current output with saved snapshot
- If output changes, test fails and shows differences
Basic Usage:
javascriptimport renderer from 'react-test-renderer'; import Button from './Button'; test('Button snapshot', () => { const tree = renderer .create(<Button>Click me</Button>) .toJSON(); expect(tree).toMatchSnapshot(); });
Inline Snapshots:
javascripttest('inline snapshot', () => { const data = { name: 'John', age: 30 }; expect(data).toMatchInlineSnapshot(` Object { "age": 30, "name": "John", } `); });
Snapshot Updates:
- Interactive update:
jest -uorjest --updateSnapshot - In CI/CD: Use
--ciflag to prevent accidental updates
Best Practices:
- Snapshots should be concise and meaningful
- Avoid including dynamic data (timestamps, IDs) in snapshots
- Regularly review and update outdated snapshots
- For large components, consider
toMatchSnapshot({mode: 'deep'}) - Use custom serializers for special objects
Use Cases:
- React/Vue component rendering tests
- API response data structure validation
- Configuration file structure verification