React Native Testing: Part 1👩‍💻

Setting up your testing environment

1. Getting started!

Let’s create a new repository by running the following command…

react-native init LocalzTesting101

2. Setting up our testing environment

When we run react-native init it automatically adds this snippet below command to our package.json allowing us to easily run our tests!
The preset just tells Jest, we are using react-native and ensures its aware of any RN specific features.


Will also need to create a .babelrc file and add in the following snippet, so babel is aware we are coding in react native.


You’ll see in your project structure, a test folder already exists! Woohoo 🎉

Here at Localz we follow convention by naming our test folders __tests__ and placing them in each folder that contains any code. So our containers, actions, reducers, components and so on, have all have their own test folders.

4. Creating a basic component

I’m going to modify the starter App.js file to look the same as below…


Now import all the needed dependencies so we can run our tests; for each of our tests we’ll also need to initialise and render our component. So lets create an init function that we can call from them — this will be handy later once we create more tests as well!


We use the snapshot to ensure consistency after mutation or functions calls.

The renderer is used to call functions from our component.

The props variable is used to pass through props to our component for testing.

5. Snapshot Testing

Now lets try out a basic snapshot test!

Snapshots work by comparing the previous file to the one just created in your test, it is fundamental that the resulting file is code reviewed properly to ensure it matches expectations.

This means that each snapshot folder produced from your tests are reviewed in a pull request and run through some sort of CI, we use Travis-CI. 😍

Above you can see we call our init() function to create our snapshot. Then using the react-native-renderer library we check it matches an existing snapshot. And thats it!

In this walkthrough, we’ve covered how to create a basic react-native project, setup our Jest testing environment and run a basic test using snapshots. I’ve created a repository containing the code above (which can be found here) if you’d like to clone and play around 👩‍💻👨‍💻

Thanks for reading! Stay tuned for Part 2 — where we will set up mocks and explore further test examples.

Like what you just read? Please give us a 👏 — it lets more people see it!
❤️ Localz