What is snapshot testing in React?
Snapshot testing is a technique where the output of a React component is captured and stored in a file (called a snapshot).
Future test runs compare the component’s output to the stored snapshot to detect unexpected changes.
How it works:
- When you first run the test, a snapshot file is generated.
- If the component changes, the next test run will detect a difference and fail the test.
- Developers can review changes and update the snapshot if they are intentional.
Example with Jest:
import { render } from '@testing-library/react'; import Header from './Header'; test('matches snapshot', () => { const { asFragment } = render(<Header />); expect(asFragment()).toMatchSnapshot(); });
Benefits:
- Easy to detect unintended UI changes.
- Great for tracking visual or structural changes over time.
Caution:
- Snapshot tests can become noisy if overused.
- They should be reviewed carefully to avoid blindly updating snapshots without understanding the changes.