Clean β’ Professional
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.
In React, snapshot tests:
.snap fileSnapshot 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();
});
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.
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:
Snapshot testing is ideal for:
Avoid snapshots for: