React Snapshot Testing
Snapshot Testing is a testing technique that captures the rendered output of a React component and saves it as a snapshot file. Later, you can compare the component’s output to ensure UI hasn’t unexpectedly changed. This is particularly useful for regression testing in React apps.
What is Snapshot Testing?
In React, snapshot tests:
- Capture the HTML structure of a component
- Save it as a
.snapfile - Alert you if the rendered output changes unexpectedly
- Work best with stateless or UI-focused components
Setting Up Snapshot Testing
Snapshot testing works with Jest, which is bundled with Create React App. No extra installation is needed.
If you don’t have Jest, install it:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
Basic Snapshot Test Example
Suppose you have a simple Button component:
// Button.jsx
import React from "react";
function Button({ label }) {
return <button>{label}</button>;
}
export default Button;
Creating a snapshot test:
// Button.test.jsx
import React from "react";
import { render } from "@testing-library/react";
import Button from "./Button";
test("renders button correctly", () => {
const { asFragment } = render(<Button label="Click Me" />);
expect(asFragment()).toMatchSnapshot();
});
Updating Snapshots
If your UI changes intentionally, Jest will fail the test. To update snapshots:
npm test -- -u
This regenerates the snapshots with the new output, keeping your tests in sync with the UI.
Snapshot Testing with React Testing Library
You can use React Testing Library to generate snapshots for more realistic rendering:
import React from "react";
import { render, screen } from "@testing-library/react";
import Button from "./Button";
test("renders button with correct label", () => {
render(<Button label="Submit" />);
const button = screen.getByText("Submit");
expect(button).toBeInTheDocument();
expect(button).toMatchSnapshot(); // Snapshot of actual DOM node
});
Benefits:
- Captures real rendered output
- Ensures UI consistency
- Detects unexpected changes automatically
When to Use Snapshot Testing
Snapshot testing is ideal for:
- Static UI components – Buttons, headers, cards
- Reusable components – Ensures consistent rendering
- Regression testing – Catch unexpected layout changes
- Documentation – Snapshots can act as visual documentation
Avoid snapshots for:
- Components with dynamic content like timestamps or live data
- Components that rely heavily on stateful logic
