SmartCodingTips

📸 Snapshot Testing in React

Snapshot testing is a technique to verify that a component’s output hasn’t changed unexpectedly. It captures a serialized version of your component's rendered output and stores it for future comparison.


🔍 1. What Is Snapshot Testing?

  • Automatically saves a "snapshot" of the rendered component
  • Compares future renders against that snapshot
  • Helps detect unintended changes in UI

⚙️ 2. Setup Requirements

You'll need jest and @testing-library/react. With Create React App, it’s already configured.

🧪 3. Basic Snapshot Example


// Button.js
export default function Button() {
  return <button>Click me</button>;
}

// Button.test.js
import { render } from '@testing-library/react';
import Button from './Button';

test('renders correctly', () => {
  const { asFragment } = render(<Button />);
  expect(asFragment()).toMatchSnapshot();
});

📁 4. What Gets Stored?

The test will generate a file in the __snapshots__ directory with the component’s HTML structure.

♻️ 5. Updating Snapshots

If your component’s UI has intentionally changed, update the snapshot with:


npm test -- -u

📌 6. When Should You Use Snapshot Testing?

  • Static and presentational components
  • Quick regressions in markup changes
  • Reusable components like buttons, cards, icons

⚠️ 7. Limitations & Cautions

  • Snapshots can become noisy and hard to manage
  • Overuse can make tests brittle and meaningless
  • Best when paired with behavior-based tests

📋 Summary

  • Snapshot testing helps catch unexpected UI changes
  • Use sparingly for UI components that change rarely
  • Run --updateSnapshot to sync snapshots with intended changes