DEV Community

Cover image for Integrating React Native App with Jest
Aneeqa Khan
Aneeqa Khan

Posted on

Integrating React Native App with Jest

Jest is a Javascript Testing Framework and it works with projects in Typescript, React, React Native, Vue, and more.
In this article, I'll cover how to install and configure jest in react native project.

Installation

For react-native projects created with init commands, it installs jest by default. But if your project doesn't have jest installed, then you can do it with this npm command.



npm install-save-dev jest


Enter fullscreen mode Exit fullscreen mode

also, check the react-native preset in added in your package.json file



{
 "scripts": {
 "test": "jest"
 },
 "jest": {
 "preset": "react-native"
 }
}


Enter fullscreen mode Exit fullscreen mode

Configuration

I used transformIgnorePatterns right below the preset of jest in the package.json file.
transformIgnorePatterns option can be used to specify which files shall be transformed by Babel. Many react-native npm modules unfortunately don't pre-compile their source code before publishing.
I have react-navigation package installed in my app so I added this regex value in transformIgnorePatterns.



"transformIgnorePatterns": [
 "node_modules/(?!(jest-)?@?react-native|@react-native-community|@react-navigation/(.*))"
]


Enter fullscreen mode Exit fullscreen mode

If you have npm dependencies that have to be transformed you can customize this configuration option by including modules other than react-native by grouping them and separating them with the | operator.

Sample function and its test

Here I created a sample function the same as they defined it in the official docs of Jest. 
I added the sum.js file and. wrote a function to simply add 2 variables and return the result.



function sum(a, b) {
 return a + b;
}
module.exports = sum;


Enter fullscreen mode Exit fullscreen mode

and wrote the sample test function sum.test.js like this



const sum = require('../src/components/atoms/sum');
jest.useFakeTimers();
test('adds 1 + 2 to equal 3', () => {
 expect(sum(1, 2)).toBe(3);
});

Enter fullscreen mode Exit fullscreen mode




Run test

Now to run the test, I wrote the npm run test command in the root folder of my project and get a result like this
run test

In the end, I just want to mention that renderer.create in the App-test.js file should always have your <App/> component as an argument. And this <App/> component must be the one which is enclosed in the <NavigationContainer> tag.
That's all, Thanks for reading, and happy coding!

Top comments (3)

Collapse
 
shabirsaddique profile image
Shabir Saddique

I appreciate your writing. Really helpful. Thanks

Collapse
 
aneeqakhan profile image
Aneeqa Khan

Thank you!

Collapse
 
flodev profile image
Florian Klenk

thanks for the article. but typescript configuration is missing :(