Course contentsShow
← React Native
Lesson 235 of 1,5553. Core Primitive ComponentsFree lesson

Implementing Component Snapshot Testing

Learners will automate visual regression testing for critical UI primitives.

In this lesson, you will learn how to automate visual regression testing for your core UI primitives to ensure your components never break unexpectedly after a refactor.

Why Snapshot Testing?

As you build a library of consistent UI components, manually checking every button, input, or card after every code change becomes impossible. Snapshot testing solves this by capturing a "photograph" of your component's rendered output (the underlying JSON tree) and saving it in a file.

The next time you run your test suite, React Native compares the new output to the saved snapshot. If even a single prop or style changes, the test will fail, alerting you that the component’s visual structure has drifted.

Setting Up a Snapshot Test

Assuming you have your testing environment ready, creating a snapshot is incredibly straightforward using react-test-renderer. Here is how you would test a custom PrimaryButton primitive:

import renderer from 'react-test-renderer';
import PrimaryButton from './PrimaryButton';

test('PrimaryButton renders correctly', () => {
  const tree = renderer.create(<PrimaryButton title="Click Me" />).toJSON();
  expect(tree).toMatchSnapshot();
});

The Workflow

  1. Initial Run: When you run this test for the first time, the framework creates a __snapshots__ folder. It saves the structure of your component there.
  2. Commit: You commit this snapshot file to your version control alongside your component code.
  3. Automated Verification: On every future run, the test compares the rendered output against that file.
  4. Updating: If you intentionally change the button's padding or color, the test will fail. If the change is intentional, you simply run a command to "update snapshots," and the file is refreshed to reflect the new design.

This gives you the confidence to refactor styles or logic within your core primitives, knowing that any accidental regression will be caught instantly before it ever reaches your users.

Key Takeaway: Snapshot testing automates the detection of visual regressions by comparing your component's rendered tree against a stored "known good" baseline.