Skip to main content

Setting Up Jest

React Native CLI installs the Jest testing framework by default, but if you're using Expo or have an older project created by React Native CLI before Jest was added, you'll need to install it manually.

Expo: Installing Jest

Install the Jest package, as well as an Expo-specific Jest preset package:

$ expo install jest-expo jest

Add the following to package.json:

   "scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
- "web": "expo start --web"
+ "web": "expo start --web",
+ "test": "jest"
},
...
"devDependencies": {
"@babel/core": "^7.12.9"
},
+ "jest": {
+ "preset": "jest-expo"
+ },
"private": true

With this, our setup should be done.

Smoke Test

To confirm Jest is working, we'll create a smoke test.

First, if a __tests__ folder exists, delete it--instead, we'll store our tests alongside our components.

Next, create a smoke.spec.js file at the root of the project. Add the following contents:

describe('truth', () => {
it('is true', () => {
expect(true).toEqual(true);
});
});

Run the tests with yarn test. You should see output like the following:

# yarn test
yarn run v1.22.19
$ jest
PASS ./smoke.spec.js
truth
✓ is true (1 ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.129 s, estimated 1 s
Ran all test suites.
✨ Done in 0.73s.

Configuring ESLint

Jest has a number of globally-available functions, so if you're using ESLint, it may complain about these.

For React Native projects, I recommend using @react-native-community/eslint-config for consistency with the majority of the React Native community. New React Native CLI projects come preconfigured with @react-native-community/eslint-config. It includes support for Jest globals.

If you're using a different ESLint config, check out eslint-plugin-jest to add support for Jest globals.

If you aren't already using ESLint in your project, it's easy to install in a React Native project. Add the following packages:

$ yarn add --dev eslint \
prettier \
@react-native-community/eslint-config

Then create an .eslintrc.js file at the root of your project and add the following:

module.exports = {
root: true,
extends: '@react-native-community',
};

Then add a .prettierrc.js file with the following:

module.exports = {
arrowParens: 'avoid',
bracketSpacing: false,
singleQuote: true,
trailingComma: 'all',
};

Most code editors can be configured to run ESLint rules as you edit. React Native CLI projects are also preconfigured with an NPM script to do so. You can add this script to Expo projects:

 "scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
- "test": "jest",
+ "test": "jest",
+ "lint": "eslint ."
},