Snapshot testing serialize output (component render, JSON object, string) và save vào .snap file — subsequent runs compare với saved snapshot, fail nếu thay đổi.
- Khi thay đổi là intentional: jest --updateSnapshot (hoặc -u) update tất cả snapshots; jest --updateSnapshot --testNamePattern để update specific.
- Inline snapshots: toMatchInlineSnapshot() lưu snapshot trong test file thay vì separate .snap file — dễ review hơn trong PRs nhưng clutters test files.
- Khi nên dùng: stable UI components ít thay đổi (Button, Card, Input), serializable data structures, API response shapes.
- Khi không nên dùng: frequently changing components (mỗi PR update snapshot không meaningful), dynamic content (timestamps, random IDs — phải mock), complex business logic (unit tests với explicit assertions tốt hơn).
- Lưu ý phổ biến: commit outdated snapshots khi developers chạy update mà không review changes — snapshot tests trở thành rubber stamp.
- Tốt nhất: kết hợp snapshot tests với explicit assertions cho critical properties.
- Enzyme vs React Testing Library: Enzyme snapshots test implementation details (component structure); RTL khuyến khích test user-visible output.
- Custom serializers: jest.addSnapshotSerializer() để format snapshot output đẹp hơn cho custom objects.
Snapshot testing serializes output (a component render, JSON object, or string) and saves it to a .snap file — subsequent runs compare the current output with the saved snapshot and fail if anything changes.
- When the change is intentional: jest --updateSnapshot (or -u) updates all snapshots; jest --updateSnapshot --testNamePattern updates specific ones.
- Inline snapshots: toMatchInlineSnapshot() stores the snapshot in the test file instead of a separate .snap file — easier to review in PRs but clutters test files.
- When to use: stable UI components that change rarely (Button, Card, Input), serializable data structures, API response shapes.
- When not to use: frequently changing components (updating snapshots every PR is not meaningful), dynamic content (timestamps, random IDs — must be mocked), complex business logic (unit tests with explicit assertions are better).
- Common pitfall: developers run the update command without reviewing the changes — snapshot tests become a rubber stamp.
- Best practice: combine snapshot tests with explicit assertions for critical properties.
- Enzyme vs React Testing Library: Enzyme snapshots test implementation details (component structure); RTL encourages testing user-visible output.
- Custom serializers: jest.addSnapshotSerializer() formats snapshot output more nicely for custom objects.