R

React Handbook

Clean • Professional

React Snapshot Testing – Capture UI Snapshots

2 minute

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 .snap file
  • 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:

  1. Static UI components – Buttons, headers, cards
  2. Reusable components – Ensures consistent rendering
  3. Regression testing – Catch unexpected layout changes
  4. 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

Article 0 of 0