1--- 2title: Unit testing 3description: Learn how to set up and configure the jest-expo package to write unit tests and snapshot tests for a project. 4--- 5 6import { Terminal } from '~/ui/components/Snippet'; 7import { BoxLink } from '~/ui/components/BoxLink'; 8 9[Jest](https://jestjs.io) is the most widely used JavaScript unit testing framework. In this guide, you'll learn how to set up Jest in your project, write a unit test, write a snapshot test, and best practices for structuring your tests when using Jest with React Native. 10 11You'll also use the `jest-expo` package which is a Jest preset and mocks the native part of the Expo SDK and handles most of the configuration. 12 13## Installation 14 15To install a compatible version of `jest-expo` for your project, run the following command: 16 17<Terminal cmd={['$ npx expo install jest-expo jest']} /> 18 19Then, update **package.json** to include: 20 21```json package.json 22"scripts": { 23 ... 24 "test": "jest" 25}, 26"jest": { 27 "preset": "jest-expo" 28} 29``` 30 31You can now start writing Jest tests. 32 33## Configuration 34 35A starting configuration you can use is to make sure any modules you are using within the **node_modules** directory are transpiled when running Jest. This can be done by including the [`transformIgnorePatterns`](https://jestjs.io/docs/configuration#transformignorepatterns-arraystring) property that takes a regex pattern as its value: 36 37```json package.json 38"jest": { 39 "preset": "jest-expo", 40 "transformIgnorePatterns": [ 41 "node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)" 42 ] 43} 44``` 45 46The above configuration should cover the majority of your needs, however, you can always add to this pattern list. 47 48Jest comes with a lot of configuration options. For more details, see [Configuring Jest](https://jestjs.io/docs/configuration). 49 50## Unit test 51 52A unit test is used to check the smallest unit of code, usually a function. 53 54To write your first unit test, start by writing a simple test for **App.js**. Create a test file for it and call it **App.test.js**. Jest identifies a file with the **.test.js** extension as a test and includes it in the tests queue. There are also other ways to [structure a test](#structure-your-tests). 55 56The test will expect the state of the `<App />` component to have one child element: 57 58```js App.test.js 59import React from 'react'; 60import renderer from 'react-test-renderer'; 61 62import App from './App'; 63 64describe('<App />', () => { 65 it('has 1 child', () => { 66 const tree = renderer.create(<App />).toJSON(); 67 expect(tree.children.length).toBe(1); 68 }); 69}); 70``` 71 72To run the test: 73 74<Terminal cmd={['$ npm run test']} /> 75 76If everything goes well, you should see the one test passed. For more information, see [expect and conditional matchers](https://jestjs.io/docs/en/expect). 77 78## Structure your tests 79 80Right now, you have a single test file in the project directory. Adding more test files can make it hard to organize your project directory. The easiest way to avoid this is to create a **\_\_tests\_\_** directory and put all your tests inside it. 81 82An example structure is shown below: 83 84```sh 85__tests__/ 86├─ components/ 87│ └─ button.test.js 88├─ navigation/ 89│ └─ mainstack.test.js 90└─ screens/ 91 └─ home.test.js 92src/ 93├─ components/ 94│ └─ button.js 95├─ navigation/ 96│ └─ mainstack.js 97└─ screens/ 98 └─ home.js 99``` 100 101However, this approach causes a lot of long import paths, such as `../../src/components/button`. 102 103Alternatively, you can have multiple **\_\_tests\_\_** sub-directories for different areas of your project. For example, create a separate test directory for **components**, **navigation**, and so on: 104 105```sh 106src/ 107├─ components/ 108├─ __tests__/ 109│ │ └─ button.test.js 110│ └─ button.js 111``` 112 113Now, if you move **\_\_tests\_\_** within the **components** directory, the import path of `<Button>` in the the **button.test.js** will be `../button`. 114 115Another option for test/file structure: 116 117```sh 118src/ 119├─ components/ 120│ ├─ button.js 121│ ├─ button.style.js 122│ └─ button.test.js 123``` 124 125It's all about preferences and up to you to decide how you want to organize your project directory. 126 127## Snapshot test 128 129A snapshot test is used to make sure that UI stays consistent, especially when a project is working with global styles that are potentially shared across components. For more information, see [snapshot testing](https://jestjs.io/docs/en/snapshot-testing). 130 131To add a snapshot test for `<App />`, add the following code snippet in the `describe()` in **App.test.js**: 132 133```js App.test.js 134it('renders correctly', () => { 135 const tree = renderer.create(<App />).toJSON(); 136 expect(tree).toMatchSnapshot(); 137}); 138``` 139 140Run `npm run test` command, and if everything goes well, you should see a snapshot created and two tests passed. 141 142## Code coverage reports 143 144Code coverage reports can help you understand how much of your code is tested. 145 146If you'd like to see code coverage report in your project using the HTML format, add the following to the **package.json**: 147 148```json package.json 149"jest": { 150 ... 151 "collectCoverage": true, 152 "collectCoverageFrom": [ 153 "**/*.{js,jsx}", 154 "!**/coverage/**", 155 "!**/node_modules/**", 156 "!**/babel.config.js", 157 "!**/jest.setup.js" 158 ] 159} 160``` 161 162Adding the above snippet allows Jest to collect coverage of all **.js** and **.jsx** files that are not inside the **coverage** or **node_modules** directories. It also excludes the **babel.config.js** and **jest.setup.js** files. You can add or remove more to this list to match your needs. 163 164Run `npm run test`. You should see a **coverage** directory created in your project. Find the **index.html** file within this directory and double-click to open it up in a browser to see the coverage report. 165 166> Usually, we don't recommend uploading **index.html** file to git. To prevent it from being tracked, you can add `coverage/**/*` in the **.gitignore** file. 167 168## Optional: Jest flows 169 170You can also use different flows to run your tests. Below are a few example scripts that you can try: 171 172```json package.json 173"scripts": { 174 ... 175 // active development of tests, watch files for changes and re-runs all tests 176 "test": "jest --watch --coverage=false --changedSince=origin/main", 177 178 // debug, console.logs and only re-runs the file that was changed 179 "testDebug": "jest -o --watch --coverage=false", 180 181 // displays code coverage in cli and updates the code coverage html 182 "testFinal": "jest", 183 184 // when a screen/component is updated, the test snapshots will throw an error, this updates them 185 "updateSnapshots": "jest -u --coverage=false" 186} 187``` 188 189For more information, see [CLI Options](https://jestjs.io/docs/en/cli) in Jest documentation. 190 191## Next step 192 193<BoxLink 194 title="React Native Testing library" 195 description="You can also use React Native Testing Library which provides testing utilities that encourage good testing practices and works with Jest." 196 href="https://github.com/callstack/react-native-testing-library" 197/> 198