Unit Testing React Native with Mocha Chai Sinon Enzyme and Istanbul 

Unit testing is an integral part of producing reliable software that meets all customer requirements when working in an agile way. Unit tests allow us to rapidly develop new functionality and add any changes without breaking existing functionality. It gives a developer the comfort that everything is still working as intended.

With “React” and especially with “React Native”, which is always changing and growing, we depend heavily on unit tests to make sense of it all. For this reason, we hope that this short guide on how to unit test React Native applications will allow you to ensure that your application code is kept stable and up to date within a rapidly changing environment.

We will cover unit testing and code coverage as well as writing an example unit test.

In 6 easy steps :

Step 1 : Setting up a react-native project.

Step 2 : Install unit testing utilities and code coverage tools.

Step 3 : Install mocks with which we test react-native components.

Step 4 : Configuring all the utilities and tools.

Step 5 : Example unit test.

Step 6 : Running your unit tests.

Step 1

NB: Make sure to version lock react to the version that react-native uses for Step 2 and Step 3. Some of the following dependencies might override it with a newer version. You can version lock react by removing the the ^ in your package.json.

Run the following command from inside your project directory:

$ npm install --save-dev mocha chai sinon enzyme istanbul@1.0.0-alpha.2

Mocha : Test framework and runner. 

Chai : Assertion library. 

Sinon : Utility for mocking and stubbing out code. Also used to set up http mocks. 

Enzyme : A utility library used to shallow render React and React Native components. 

Istanbul : A code coverage generator that works well with mocha. We explicitly use the @1.0.0-alpha.2 version which supports JSX.

I would recommend reading up on the basics of how each of these libraries should be used and how to use them. You have to be well acquainted with these libraries in order to effectively write unit tests.

Step 3

Install the additional dependencies that are required to mock out React Native components. These libraries will act as a good foundation allowing us to test most of the basic React Native components.

Run the following command from inside your project directory: (Replace xxx with the version number of React used by React Native.)

$ npm install --save-dev react-dom@xxx react-native-mock

Step 4

Before we start doing any configuration first have a look at your package.json and make sure it is similar to the following :



@TangentSolutions


@TangentSolutions


@TangentSolutions


@TangentZA