During the past year and as part of our philosophy of continuous improvement, we have been conducting various shared-training sessions, in which our team members themselves share their knowledge, experiences and ideas. As we know, constant training and continuous learning are essential to keep up to date in a constantly evolving technological world.

In this series of posts, we will discuss some key aspects of these sessions.

Training Pill 05:

Application testing in React Native

Teach:

Luis Marín

Installation:
Since React Native version 0.38, Jest comes installed and configured in our package.json by default.

If we want to install it or migrate an older React Native app we must install it via Yarn or Npm.

yarn add –dev jest babel-jest

The first dependency is Jest itself and the second one the
Jest plugin for Babel.

With this plugin the tests will be automatically transpiled using Babel without having to add any extra configuration.

In our package.json afterwards we will have to have a structure like this:

Regression test with component captures.

A remarkable feature of Jest compared to other testing frameworks is the possibility to perform regression tests on the components.

To render our components we will use react-test- renderer that allows us to render a component and obtain its representation in json.

yarn add –dev react-test-renderer

Next we are going to create our first test, the __tests__ folder in the root is where Jest looks for the tests by default.

To run the tests we use one of the scripts defined in our package.json in the key “scripts”, in this case the script “test” was associated to the execution of “jest”:

npm run test

In the test we render the <Loading /> component, get its json representation and compare it with a snapshot. As the test has never been run before, on the first test run the snapshot file will be created and the test will pass.

In the same folder where the test is, a __snapshots__ directory will have been created where the representation of this component will be. In the next test run the current result will be compared with the previous one.

In case we change the component the test will fail, in this case we are going to slightly change a property in the Loading component to see the test result.

If this is the result that we want our component to have from now on we must regenerate the snapshots so that it takes the current state as the correct one.

node node_modules/jest/bin/jest.js –updateSnapshot

Note: This command updates all snapshots, it is important to run the tests before and see that only the desired components fail.

Admin