React Native Snapshot Tests

Marius Reimer

--

There are different ways to test your React Native app, where each way targets a specific use case. You can test a single part (unit test) or a collection of units, that act together (integration test). If you want to test an app as a whole, in a real device or simulator, end-to-end tests are often used.

Components, which are a central part of a React Native app, can also be tested. There are libraries like the react-native-testing-library, that can render your components without a simulator or device, which speeds up the tests and makes them more reliable. Actions and render-update behaviour can be tested, which is an integral part of a component.

Use the code “reime005-medium” to get 70% discount on my Ultimate React Native Testing Guide on Gumroad.

Rendering a component and comparing its output against a reference output, is called snapshot test. The rendered output is often saved in the project and updated if necessary. Alternatively, you could do inline snapshots. The goal of these kind of tests is simply to make sure that your component renders and does not change unexpectedly.

For example, a change in an app theme could cause an unexpected change in one of your components, that you otherwise would have not noticed so fast. You then can check this component specifically and update the snapshot, if the change was fine.

Lets consider this simple React Native component, which is a wrapper around an ActivityIndicator:

const Spinner = () => {
const theme = useTheme();

return <ActivityIndicator color={theme.secondaryColor} size="large" />
};

The Spinner consumes the app theme using the useTheme hook. A change in the secondaryColor property would cause the color of the indicator to be different. With a simple snapshot test, you could catch this issue. A snapshot could look like the following:

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Spinner should render 1`] = `
<ActivityIndicator
color="white"
size="large"
/>
`;

An the test case could look like the following:

describe('Spinner', () => {
it('should render', () => {
render(<Spinner />);

expect(screen.toJSON()).toMatchSnapshot();
});
});

This helps a lot with making sure that your UI does not change unexpectedly. You simply need to integrate the react-native-testing-library as described here.

--

--

No responses yet