| name | testing-snapshot-testing-jest |
| description | Imported TRAE skill from testing/Snapshot_Testing_Jest.md Use when this capability is needed. |
| metadata | {"author":"Ditto190"} |
Skill: Snapshot Testing (Jest)
Purpose
To ensure that your UI components or data structures don't change unexpectedly. Snapshot testing records the rendered output of a component and compares it against a saved "baseline" version in future test runs.
When to Use
- When testing React, Vue, or Angular components to catch unintended HTML/CSS changes
- When validating complex JSON API responses that have a stable structure
- To document the expected output of a function without writing dozens of manual assertions
Procedure
1. Basic Component Snapshot
Use toMatchSnapshot() in your Jest tests.
import { render } from '@testing-library/react';
import { MyComponent } from './MyComponent';
test('renders correctly', () => {
const { asFragment } = render(<MyComponent name="John" />);
expect(asFragment()).toMatchSnapshot();
});
2. Snapshotting Data Structures
Snapshots aren't just for UI. They are great for complex objects.
test('api response has correct shape', () => {
const complexObject = generateReport(data);
expect(complexObject).toMatchSnapshot();
});
3. Inline Snapshots
If the output is small, use toMatchInlineSnapshot() to keep the baseline directly in your test file.
test('formats currency', () => {
const result = formatCurrency(10.5);
expect(result).toMatchInlineSnapshot(`"$10.50"`);
});
4. Updating Snapshots
When you intentionally change a component's design, update the snapshots via CLI.
npm test -- -u
jest --updateSnapshot
Best Practices
Source: Ditto190/crispy-nextjs-turborepo-monorepo — distributed by TomeVault.