Setting Up Jest in a React Native Project
Configure Jest with the react-native preset, run your first test file, understand the test, describe, and expect API, and set up code coverage reporting.
Why Testing React Native Code
Tests are your safety net when making changes. A well-written test suite lets you refactor confidently, catch regressions before they reach users, and document expected behavior for your teammates. For React Native specifically, tests are especially valuable because running the full app on a simulator is slow compared to running unit tests.
There are three levels of testing in React Native: unit tests (individual functions and hooks), component tests (rendering components and asserting on output), and end-to-end tests (driving the real app on a device). Jest handles the first two.
Jest Comes Pre-Configured
React Native projects created with the React Native CLI or Expo SDK already include Jest. You will find jest in devDependencies and a Jest configuration in package.json under the 'jest' key, or in a jest.config.js file.
The preset 'react-native' (from @react-native/jest-preset) or 'jest-expo' (for Expo) configures Jest to transform JSX and handle native module mocks automatically. Always use the appropriate preset for your project type.
// package.json (React Native CLI project)
{
'jest': {
'preset': 'react-native'
}
}
// package.json (Expo project)
{
'jest': {
'preset': 'jest-expo',
'transformIgnorePatterns': [
'node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*)'
]
}
}All lessons in this course
- Setting Up Jest in a React Native Project
- Rendering Components with React Native Testing Library
- Firing Events and Testing User Interaction
- Mocking Native Modules and Async Code