Unit Testing in React Native: A Complete Guide

Introduction

Unit testing ensures that individual components and functions in your React Native app work correctly. Writing unit tests can:
✅ Prevent unexpected bugs
✅ Improve app stability
✅ Simplify debugging

In this guide, we’ll cover:
✔️ Why unit testing is important in React Native
✔️ Setting up Jest for testing
✔️ Writing unit tests for components and functions
✔️ Mocking dependencies
✔️ Running tests and debugging


1. Why Unit Testing in React Native?

Unit tests help developers:
✔️ Catch bugs early before deployment
✔️ Ensure UI components behave as expected
✔️ Validate logic without running the full app
✔️ Improve confidence in refactoring code

Tools for Unit Testing in React Native:

  • Jest – Default test runner for React Native
  • React Test Renderer – Renders components for testing
  • Testing Library/React Native – Simulates user interactions

2. Setting Up Jest in a React Native Project

Step 1: Install Jest and Dependencies

React Native comes with Jest pre-configured, but if it’s missing, install it manually:

npm install --save-dev jest @testing-library/react-native @testing-library/jest-native

For TypeScript projects, also install:

npm install --save-dev @types/jest

Step 2: Update Jest Configuration

Modify package.json:

"jest": {
"preset": "react-native",
"setupFilesAfterEnv": ["@testing-library/jest-native/extend-expect"]
}

Create a setup file jest.setup.js (for additional configurations if needed):

import "@testing-library/jest-native/extend-expect";

3. Writing Unit Tests in React Native

Testing a Simple Function

Create a utility function sum.js:

export const sum = (a, b) => a + b;

Create a test file sum.test.js:

import { sum } from './sum';

test(‘adds 2 + 3 to equal 5’, () => {
expect(sum(2, 3)).toBe(5);
});

Run the test:

npm test

4. Testing a React Native Component

Create a simple componentButton.js:

import React from 'react';

import { Text, TouchableOpacity } from ‘react-native’;
const Button = ({ title, onPress }) => (
<TouchableOpacity onPress={onPress} testID=“button”>
<Text>{title}</Text>
</TouchableOpacity>

);

export default Button;

Create a test file Button.test.js:

import React from 'react';

import { render, fireEvent } from ‘@testing-library/react-native’;
import Button from ‘../Button’;

test(‘Button renders correctly and triggers onPress’, () =>
{

const mockPress = jest.fn();
const { getByTestId } = render(<Button title=“Click Me” onPress={mockPress} />);
const button = getByTestId(‘button’);
fireEvent.press(button);
expect(mockPress).toHaveBeenCalled();

});

5. Mocking Dependencies in React Native Tests

Mock external libraries like Axios:

jest.mock('axios');
import axios from 'axios';
axios.get.mockResolvedValue({ data: { message: 'Success' } });

Mock Async Storage:

jest.mock('@react-native-async-storage/async-storage', () => ({

getItem: jest.fn(),
setItem: jest.fn()
}));

6. Running and Debugging Tests

Run Jest tests:

npm test

Run tests with watch mode for continuous updates:

npm test -- --watch

Run a specific test file:

npm test Button.test.js

Debug failing tests:

npm test -- --verbose

7. Best Practices for Unit Testing in React Native

✔️ Write small, independent tests
✔️ Use test IDs (testID prop) for selecting UI elements
✔️ Mock network requests to avoid API calls in tests
✔️ Ensure 100% code coverage for critical logic

Conclusion

Unit testing in React Native improves code quality and prevents regressions. By using Jest and Testing Library, you can write reliable tests for both UI components and business logic.

You may also like

Leave a Reply