乐闻世界logo
搜索文章和话题

What is Jest snapshot testing? How to use snapshot testing to verify component output?

2月21日 15:54

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:

javascript
import 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:

javascript
test('inline snapshot', () => { const data = { name: 'John', age: 30 }; expect(data).toMatchInlineSnapshot(` Object { "age": 30, "name": "John", } `); });

Snapshot Updates:

  • Interactive update: jest -u or jest --updateSnapshot
  • In CI/CD: Use --ci flag 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
标签:Jest