Snapshot testing helps you check if your app's screen or component looks the same as before. It catches unexpected changes easily.
0
0
Snapshot testing in React Native
Introduction
When you want to make sure a UI component does not change after code updates.
When you add new features and want to confirm old screens still look right.
When fixing bugs to verify the fix does not break the UI.
When refactoring code to keep the UI consistent.
When collaborating with others to track UI changes clearly.
Syntax
React Native
import React from 'react'; import renderer from 'react-test-renderer'; import MyComponent from '../MyComponent'; test('renders correctly', () => { const tree = renderer.create(<MyComponent />).toJSON(); expect(tree).toMatchSnapshot(); });
Use renderer.create() to render the component in a test environment.
toMatchSnapshot() compares the rendered output to a saved snapshot file.
Examples
Tests if the Button component renders the same as before.
React Native
test('button snapshot', () => { const tree = renderer.create(<Button title="Click" />).toJSON(); expect(tree).toMatchSnapshot(); });
Checks if the TextInput component UI stays consistent.
React Native
test('text input snapshot', () => { const tree = renderer.create(<TextInput placeholder="Name" />).toJSON(); expect(tree).toMatchSnapshot(); });
Sample App
This test renders a simple Greeting component and saves its UI structure as a snapshot. Later runs compare the UI to this snapshot to detect changes.
React Native
import React from 'react'; import renderer from 'react-test-renderer'; import { Text, View } from 'react-native'; function Greeting() { return ( <View> <Text>Hello, friend!</Text> </View> ); } test('Greeting renders correctly', () => { const tree = renderer.create(<Greeting />).toJSON(); expect(tree).toMatchSnapshot(); });
OutputSuccess
Important Notes
Snapshots are saved as files in a __snapshots__ folder next to your test files.
If UI changes are expected, update snapshots by running tests with --updateSnapshot flag.
Keep snapshots small and focused on one component to avoid large, hard-to-read files.
Summary
Snapshot testing helps catch unexpected UI changes quickly.
It saves a rendered UI output and compares future renders to it.
Use it to keep your app's look consistent during development.