React Native Testing With Jest

Jahanzaib Iqbal Gondal
3 min readJul 6, 2021

In React Native versions 0.38 and greater, Jest is included when creating a project via react-native init, so the following setup may be already done for you. Same goes if you’ve read the documentation from Jest on setting up testing with React Native

you can also check in package.json

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

Step#1

yarn add --dev react-native-testing-library

step # 2 Writing your first test

open file folder __tests__/App-test.js which is in root of project , now edit file and paste

import 'react-native';import React from 'react';import AddAnnotationModel from '../src/components/Model/AddAnnotationModel';import { render, fireEvent } from "@testing-library/react-native";it('Simple example', () => {const test = 2 + 2expect(test).toEqual(4);});

if we change and try to fail test , now we want test variable value to 3

import 'react-native';import React from 'react';import AddAnnotationModel from '../src/components/Model/AddAnnotationModel';import { render, fireEvent } from "@testing-library/react-native";it('Simple example', () => {const test = 2 + 2expect(test).toEqual(3);});

here is result

Here is another Example

in this example we have u.i where we add tags to array , like video search tags

code is here when test pass

import 'react-native';import React from 'react';import AddAnnotationModel from '../src/components/Model/AddAnnotationModel';import { render, fireEvent } from "@testing-library/react-native";it('Should create an item', () => {const { getByText, getByPlaceholderText } = render(<AddAnnotationModel />)const addItemButton = getByText('Add Tags')const textInput = getByPlaceholderText('Enter Search tag for annotation')const centerItemText = '1st';fireEvent.changeText(textInput, centerItemText);fireEvent.press(addItemButton)const createdItem = getByText(centerItemText)expect(createdItem).not.toBeNull();});

here is out result when test pass

code is here when test fail , just updating last condition createdItem variable text let see what happen now

import 'react-native';import React from 'react';import AddAnnotationModel from '../src/components/Model/AddAnnotationModel';import { render, fireEvent } from "@testing-library/react-native";it('Should create an item', () => {const { getByText, getByPlaceholderText } = render(<AddAnnotationModel />)const addItemButton = getByText('Add Tags')const textInput = getByPlaceholderText('Enter Search tag for annotation')const centerItemText = '1st';fireEvent.changeText(textInput, centerItemText);fireEvent.press(addItemButton)const createdItem = getByText('change in text')expect(createdItem).not.toBeNull();});

here is out result when test fail

--

--