Snapshot Testing in React
Last Updated :
19 Aug, 2025
Snapshot testing is the testing technique used in React that captures the rendered output of a component and compares it to a previously saved "snapshot" of that output.
Features of Snapshot Testing
- Render the component: Jest renders the React component in a controlled test environment.
- Capture the snapshot: A snapshot (JSON of the DOM) is taken of the rendered component.
- Store the snapshot: Snapshots are saved in a snapshots folder.
- Compare on subsequent runs: Jest re-renders and compares the new output with the saved snapshot, passing if they match and failing if there are differences.
Setting Up Snapshot Testing
Here are the steps to set up snapshot testing in React:
1. Create a React Project
npx create-react-app react-app
cd snapshot-testing-demo
2. Install Dependencies
Install Jest and React Test Renderer:
npm install --save-dev @testing-library/react @testing-library/jest-dom jest
3. Create a Simple Component
Create a React component that we will test.
JavaScript
//Button.js
import React from "react";
const Button = ({ label }) => {
return <button>{label}</button>;
};
export default Button;
4. Write a Snapshot Test
Create a test file for the component inside the __tests__ directory.
JavaScript
import React from "react";
import { render } from "@testing-library/react";
import Button from "../components/Button";
test("Button component renders correctly", () => {
const { asFragment } = render(<Button label="Click me" />);
expect(asFragment()).toMatchSnapshot();
});
Folder Structure

5. Run the Snapshot Test
npm test
Jest creates a snapshot file inside the __snapshots__ folder, if the test passes.
exports[`Button component renders correctly 1`] = `
<button>
Click me
</button>
`;6. Handling Snapshot Updates
If the component changes (e.g., new props or UI updates), the test will fail.
npm test -- -u
Output
snapshot testing in React.In this example
- The Button component is a simple React component that takes a label prop and renders a <button> element with the label text passed to it.
- The test is written using React Testing Library and Jest. It imports the render function from @testing-library/react and the Button component.
- The test renders the Button component with a label ("Click me") using render(<Button label="Click me" />).
- The asFragment() method is used to capture the rendered output as a snapshot, and expect(asFragment()).toMatchSnapshot() checks if the rendered output matches the saved snapshot. If it changes, the test will fail, helping detect unintended changes.
Limitations of Snapshot Testing
Below are the limitations of snapshot testing:
- False Positives: Tests may pass even if the UI has minor, unintended changes that aren't easily noticeable.
- Overhead in Large Snapshots: Large snapshots can be difficult to manage and review.
- Not a Substitute for Functional Testing: Snapshot tests verify the structure, not the functionality, of components.