How to Set Up Jest and Enzyme to Test React Native Apps

Testing is an essential part of developing quality software. For React Native apps specifically, having automated tests in place helps catch issues early, enables safe refactoring of code, and gives developers confidence when shipping new features.

In this comprehensive guide, I‘ll walk you through how to set up and configure Jest (a popular JavaScript testing framework) and Enzyme (a useful companion library) to test React Native components.

Overview of the React Native Testing Landscape

Before jumping into the setup, it‘s helpful to understand the overall React Native testing ecosystem.

There are a few main types of automated tests used with React Native apps:

Unit Tests – Test individual components in isolation. Help catch issues early and enable safe refactoring. Jest and Enzyme shine here.

Integration Tests – Test how components interact. Useful for verifying complex flows work as expected.

UI Tests – Simulate user interactions and assert on the UI. Helps catch visual regressions. Common tools are Detox and Appium.

Snapshot Tests – Capture rendered component markup and compare to previously saved snapshots. Flag unexpected differences. Jest snapshots are popular.

For unit testing specifically, Jest and Enzyme are very common choices. Let‘s look at why:

Why Use Jest for Testing React Native

Jest is a comprehensive, well-maintained JavaScript testing framework created by Facebook. Some of its useful features include:

  • Comes preconfigured with React Native projects
  • Built-in assertions, spies, and mocks
  • Fast interactive watch mode
  • Snapshots to detect UI changes
  • Code coverage reports
  • Works nicely with Continuous Integration

Overall, Jest makes writing and running tests smooth and intuitive. And since React Native itself uses Jest for testing, it‘s a natural fit to adopt.

Why Add Enzyme for Unit Testing

While Jest provides a fantastic testing framework, Enzyme is very helpful for making actual test writing easier. Think of Enzyme as a utility belt for React/React Native unit testing.

Some of Enzyme‘s benefits:

  • Simplifies selecting, traversing, and manipulating components
  • Avoid brittle tests when internal implementation details change
  • Intuitive API to mimic user interactions
  • Extensible to support various test runners and assertions

Together, Jest and Enzyme provide an excellent combination for testing React Native app components.

Step-by-Step Guide to Configure Jest and Enzyme

Now that there is context on why Jest and Enzyme are useful, let‘s go through the setup process step-by-step.

The goals are to:

  1. Get Jest fully configured for React Native
  2. Get Enzyme installed and integrated
  3. Set up enzyme-adapter-react-16 to translate between React and Enzyme
  4. Confirm everything is wired properly with a simple test

Prerequisites

To follow along, you‘ll need:

  • React Native project created with react-native init
  • Node.js installed (version 10+)
  • Understanding of React basics

With those in place, let‘s get started!

1. Confirm Jest is Preconfigured

React Native projects generated with react-native init come preconfigured with Jest out of the box.

Double check by opening your package.json file and validating the following is present:

"jest": {
  "preset": "react-native"
}

The "preset": "react-native" part sets up some default Jest config tailored for React Native apps, like properly handling .js files and mapping common mock libraries.

If for some reason that preset line wasn‘t there automatically, simply add it yourself.

With the preset configured, Jest is ready to test React Native components!

2. Install Enzyme and Adapter

Now install Enzyme and the React 16 adapter with:

npm install --save-dev enzyme react-dom enzyme-adapter-react-16

Breaking this down:

  • enzyme – Core Enzyme library
  • react-dom – Required peer dependency
  • enzyme-adapter-react-16 – Connects Enzyme to React 16

Note: I also recommend installing the enzyme-to-json package for easy snapshot testing:

npm install --save-dev enzyme-to-json

3. Connect Enzyme with Jest

Next we need to hook up Jest to work with Enzyme. This consists of two parts:

A. Setup Test Environment

In package.json specify the test environment:

"testEnvironment": "enzyme", 

This tells Jest to load Enzyme‘s custom test environment when running tests.

B. Configure Enzyme Adapter

Still in package.json, add an enzymeAdapter entry:

"enzymeAdapter": "react16"

This ensures the React 16 Enzyme adapter gets used.

Bringing it all together, your full Jest config should now look like:

"jest": {
  "preset": "react-native",
  "testEnvironment": "enzyme", 
  "enzymeAdapter": "react16" 
}

And with that, Jest and Enzyme are fully integrated!

4. Write a Simple Snapshot Test

To validate everything is working properly, let‘s write a simple snapshot test.

A. Create Test File

Inside your __tests__ folder, create a Hello.test.js file with:

import React from ‘react‘;
import { shallow } from ‘enzyme‘;
import Hello from ‘../Hello‘;

it(‘renders correctly‘, () => {
  const wrapper = shallow(<Hello />);

  expect(wrapper).toMatchSnapshot(); 
});

B. Add Component File

Then define a simple Hello component in Hello.js:

import React from ‘react‘;
import { Text } from ‘react-native‘;

const Hello = () => {
  return <Text>Hello World!</Text>; 
};

export default Hello;

C. Run Test

Finally, run the test with npm test and validate it passes:

> npm test

> ...

β€Ί 1 snapshot written.
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   66.67 |      100 |      50 |   66.67 |                   
 Hello.js |   66.67 |      100 |      50 |   66.67 | 4                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total

The key things to check are:

  • Test passes
  • 1 snapshot gets written
  • Snapshot summary looks correct

If you see those indications, Jest and Enzyme are good to start testing!

Next Steps for Testing React Native Apps

And that wraps up the core setup! At this point Jest and Enzyme are ready to start testing React Native components and business logic.

Here are some recommended next steps:

  • Write More Unit Tests – Test key components, reducers, utils, etc
  • Learn Enzyme APIs – Dig into Enzyme‘s powerful APIs like find, props, state, etc
  • Mock Dependencies – Use Jest manual mocks to isolate code under test
  • Try Snapshot Testing – Lean on snapshot tests to catch UI regressions
  • Integrate with CI – Run test suites on every code change with GitHub Actions

Adding comprehensive automated testing delivers huge long term dividends for app stability, refactoring agility, and developer productivity.

Hopefully this gives you a smooth on-ramp to start unit testing your React Native apps using the power of Jest and Enzyme!

Please reach out in the comments with any setup questions. Happy testing!

Similar Posts