Table of contents

TL;DR

  • Why it matters: Automated testing in React Native helps catch bugs early, supports faster development, and improves team collaboration.
  • Tools used: Jest, React Native Testing Library (RTL), and @testing-library/jest-native for simulating user behavior.
  • Setup made easy: Quick configuration with jest.config.js and a few dev dependencies gets you started in minutes.
  • Real-world examples: Learn to test buttons, inputs, state updates, and async API calls using fireEvent and waitFor.
  • Best practices: Keep tests focused, use user-centric queries, and mock external dependencies for clean, reliable test coverage.

Introduction 

Building and scaling React Native apps comes with its share of challenges—but maintaining code quality shouldn’t be one of them. As apps grow more complex, having automated tests in place helps catch bugs early, speeds up development, and reduces the risk of regressions.

Testing is now a core part of the development workflow for many teams working on production-grade apps. Whether you’re shipping in-house or partnering with a React Native app development company, reliable tests make collaboration easier and refactoring safer.

In this guide, we’ll cover how to set up unit testing in React Native using Jest and React Native Testing Library (RTL), write clean and focused test cases, and handle common patterns like user input and async behavior—all with real examples you can apply to your own codebase.


Why Testing Matters

React Native apps grow quickly, and without tests, it’s easy to break something unknowingly. Testing gives you:

  • Faster development with instant feedback
  • More confidence in code changes and refactoring
  • Better collaboration in teams with fewer bugs

And when paired with continuous integration, tests become your first line of defense.


Tools We’ll Use

  • Jest – A fast testing framework from Meta with built-in mocking
  • React Native Testing Library (RTL) – A powerful library to test components the way users interact with them
  • @testing-library/jest-native – Helpful matchers like toBeVisible() and toHaveTextContent()

Setting Up Your Project

Make sure you have a React Native project ready (either Expo or bare React Native). Then install the required dev dependencies:

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

Add Jest Config

You can configure Jest in jest.config.js or directly in package.json:

// jest.config.js

module.exports = {

  preset: 'react-native',

  setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'],

  transformIgnorePatterns: [

    'node_modules/(?!(jest-)?react-native|@react-native|@react-navigation)',

  ],

};

This tells Jest how to handle React Native files and makes matchers like toBeVisible() available.


Writing Your First Test

Let’s start with a simple button component.

// ButtonComponent.js

import React from 'react';

import { Button } from 'react-native';

export default function ButtonComponent({ onPress }) {

  return <Button title="Click me" onPress={onPress} />;

}

Now write a test to check if pressing the button triggers the onPress function:

// ButtonComponent.test.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react-native';
import ButtonComponent from './ButtonComponent';

test('calls onPress when clicked', () => {
  const mockFn = jest.fn();
  const { getByText } = render(<ButtonComponent onPress={mockFn} />);
  
  fireEvent.press(getByText('Click me'));
  expect(mockFn).toHaveBeenCalledTimes(1);
});

This test simulates a press and confirms that the onPress handler is called exactly once.


Testing Text Input and State Updates

Let’s add a component that uses state and a TextInput

// ButtonComponent.js

import React from 'react';

import { Button } from 'react-native';

export default function ButtonComponent({ onPress }) {

  return <Button title="Click me" onPress={onPress} />;

}

Here’s how you’d test it:

// GreetingInput.test.js

import React from 'react';

import { render, fireEvent } from '@testing-library/react-native';

import GreetingInput from './GreetingInput';

test('updates greeting when name is typed', () => {

  const { getByPlaceholderText, getByText } = render(<GreetingInput />);

  const input = getByPlaceholderText('Enter your name');

  fireEvent.changeText(input, 'Alice');

  expect(getByText('Hello, Alice')).toBeTruthy();

});

This test ensures that the state updates correctly and the greeting reflects the typed name.


Mocking API Calls and Async Functions

For components that fetch data, use jest.mock() and async utilities like waitFor.

Example with a fake fetch:

jsx

// UserProfile.js

import React, { useEffect, useState } from 'react';

import { Text } from 'react-native';

export default function UserProfile() {

  const [name, setName] = useState('');

  useEffect(() => {

    fetch('https://example.com/user')

      .then(res => res.json())

      .then(data => setName(data.name));

  }, []);

  return <Text>{name ? `Welcome, ${name}` : 'Loading...'}</Text>;

}

Now test it:

// UserProfile.test.js

import React from 'react';

import { render, waitFor } from '@testing-library/react-native';

import UserProfile from './UserProfile';

global.fetch = jest.fn(() =>

  Promise.resolve({

    json: () => Promise.resolve({ name: 'Charlie' }),

  })

);

test('displays user name after fetch', async () => {

  const { getByText } = render(<UserProfile />);

  await waitFor(() => expect(getByText('Welcome, Charlie')).toBeTruthy());

});

Using waitFor ensures the test waits for the async fetch to complete.


Common Pitfalls & Best Practices

  • Use getByRole, getByText, or getByPlaceholderText to select elements like a real user would
  • Use waitFor or findByText for async updates instead of setTimeout
  • Keep tests small and focused — one behavior per test
  • Use mocks for external dependencies (like APIs, animations)

Conclusion

Unit testing in React Native doesn’t have to feel overwhelming. With tools like Jest and React Native Testing Library, you can replicate real user interactions, validate component behavior, and catch issues before they reach production.

By making testing a part of your workflow, you’ll not only improve code quality but also move faster with greater confidence. And if you’re scaling your project and need expert help, you can hire React Native developers who follow these best practices from day one.

Have questions or need help getting started? Book a free 30-minute consultation to explore how testing can fit into your development workflow.


Mobile
React Native
Sagar Makwana
Sagar Makwana

Software Engineer

Launch your MVP in 3 months!
arrow curve animation Help me succeed img
Hire Dedicated Developers or Team
arrow curve animation Help me succeed img
Flexible Pricing
arrow curve animation Help me succeed img
Tech Question's?
arrow curve animation
creole stuidos round ring waving Hand
cta

Book a call with our experts

Discussing a project or an idea with us is easy.

client-review
client-review
client-review
client-review
client-review
client-review

tech-smiley Love we get from the world

white heart