Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 71 ยท Quality

Testing React Native Apps

Test React Native apps with Jest and React Native Testing Library, mock native modules, and learn when end-to-end tools like Maestro and Detox are worth it.

A mobile app is expensive to fix after release. You cannot hot-patch a store build the way you redeploy a website: a bad version sits on thousands of phones until a new one is reviewed and installed. Automated tests are your safety net, and the good news is that most of React Native can be tested on your computer in a second, without a simulator.

This lesson builds a testing pyramid for mobile: fast unit and component tests with Jest and React Native Testing Library (RNTL) at the bottom, a few end-to-end flows with Maestro or Detox at the top. You will learn how to query components the way a user sees them, how to mock native modules such as notifications and the camera, and how to keep tests from becoming brittle.

Read-only and stand-in. Jest and RNTL run on Node with a mocked native layer, and end-to-end tools drive a real simulator, so none of them run on this page. The real configuration and tests are shown in plain blocks. The TryIts run a tiny test runner and a tiny testing library written for the browser, in the same style, so you can see how describe, it, expect, getByRole and fireEvent.press work inside.

The mobile testing pyramid

Different tests answer different questions, at different costs.

Level Tool Runs on Speed Catches
Unit Jest Node milliseconds Logic bugs in functions and reducers
Component Jest + RNTL Node, native layer mocked tens of milliseconds Wrong text, broken presses, missing states
End to end Maestro or Detox Simulator or real device seconds to minutes Broken builds, navigation, native permissions

Write many of the cheap kind, a moderate number of component tests for each screen's states, and a handful of end-to-end flows for the journeys that make or lose money: sign up, log in, check out.

The testing pyramid

Unit tests Many, fast, pure logic.
Component tests Each screen and its states.
End to end A few key journeys on a device.

The higher you go, the slower and costlier the test.

1 / 2

Setting up Jest

Expo projects use the jest-expo preset, which sets up the transformer and mocks the core native modules. Install and configure it once:

Terminal
npx expo install jest-expo jest @types/jest --dev
npm install --save-dev @testing-library/react-native
JSON
{
  "scripts": { "test": "jest" },
  "jest": {
    "preset": "jest-expo",
    "setupFilesAfterEnv": ["<rootDir>/jest.setup.ts"]
  }
}

Plain React Native (without Expo) uses "preset": "react-native". Test files end in .test.ts or .test.tsx, or live in a __tests__ folder. If a test fails with a syntax error coming from node_modules, the usual cause is a package that ships untranspiled code: add it to transformIgnorePatterns so Jest transforms it too.

Unit tests: pure logic first

The cheapest wins are plain functions, such as a reducer or a formatter. Pull logic out of components and test it directly, as you did for the state helpers in State in React Native Apps.

TypeScript
// cart.ts
export type Line = { id: string; price: number; qty: number };

export function total(lines: Line[]): number {
  return lines.reduce((sum, line) => sum + line.price * line.qty, 0);
}
TypeScript
// cart.test.ts
import { total } from './cart';

describe('total', () => {
  it('returns 0 for an empty cart', () => {
    expect(total([])).toBe(0);
  });

  it('adds price times quantity for every line', () => {
    const lines = [
      { id: 'a', price: 5, qty: 2 },
      { id: 'b', price: 3, qty: 1 },
    ];
    expect(total(lines)).toBe(13);
  });
});

describe groups tests, it (or test) is one test, and expect(value).toBe(expected) checks a result. A test passes when it finishes without a failed expectation or a thrown error.

Component tests with React Native Testing Library

RNTL renders your component into a fake native tree (no phone, no simulator) and gives you queries that mirror what a person perceives. A person sees a button called "Save", a text field labeled "Email", a message that says "Welcome"; they do not see component names or state variables.

TSX
// Counter.tsx
import { useState } from 'react';
import { Pressable, Text, View } from 'react-native';

export function Counter() {
  const [count, setCount] = useState(0);
  return (
    <View>
      <Text>Count: {count}</Text>
      <Pressable accessibilityRole="button" onPress={() => setCount(count + 1)}>
        <Text>Add one</Text>
      </Pressable>
    </View>
  );
}
TSX
// Counter.test.tsx
import { fireEvent, render, screen } from '@testing-library/react-native';
import { Counter } from './Counter';

it('increments when the button is pressed', () => {
  render(<Counter />);
  expect(screen.getByText('Count: 0')).toBeOnTheScreen();

  fireEvent.press(screen.getByRole('button', { name: 'Add one' }));

  expect(screen.getByText('Count: 1')).toBeOnTheScreen();
});

The queries come in three families:

  • getBy... returns the element or throws if it is missing (or if there are several matches).
  • queryBy... returns null when it is missing, which is what you use to assert that something is absent: expect(screen.queryByText('Error')).not.toBeOnTheScreen().
  • findBy... is asynchronous: it waits until the element appears (for data that loads), then returns it: await screen.findByText('Maya').

Prefer queries in this order: getByRole, getByLabelText, getByText, getByPlaceholderText, and only then getByTestId. A role-based query doubles as an accessibility check, because it only works if you gave the element a role and a name (see Accessibility in React Native). A test that finds the button by its role will keep passing when you restyle it, and will fail if you accidentally break its accessibility.

For realism, RNTL also offers userEvent, which simulates the whole sequence of a real press or typing session (focus, press in, press out), while fireEvent just calls the handler. Use userEvent when timing matters, fireEvent.press for simple cases.

Testing async screens

Most screens load data. Mock the network function, render, and wait for the result:

TSX
import { render, screen } from '@testing-library/react-native';
import { Profile } from './Profile';
import * as api from './api';

it('shows the name after loading', async () => {
  jest.spyOn(api, 'fetchUser').mockResolvedValue({ name: 'Maya' });

  render(<Profile userId={7} />);

  expect(screen.getByText('Loading...')).toBeOnTheScreen();
  expect(await screen.findByText('Maya')).toBeOnTheScreen();
});

it('shows an error message when the request fails', async () => {
  jest.spyOn(api, 'fetchUser').mockRejectedValue(new Error('offline'));

  render(<Profile userId={7} />);

  expect(await screen.findByText('Could not load the profile')).toBeOnTheScreen();
});

Test the states a screen can be in (loading, success, error, empty), not just the happy path. Those are the states users complain about. For timers (debounce, auto-dismissing toasts), use jest.useFakeTimers() and advance the clock with jest.advanceTimersByTime(500) inside act, so tests never wait for real time.

Mocking native modules

On your computer there is no camera, no notification service and no secure storage. The jest-expo preset mocks the core ones, but the libraries you add may need a mock of their own. Put shared mocks in jest.setup.ts, or mock per test file with jest.mock.

TypeScript
// jest.setup.ts
jest.mock('expo-notifications', () => ({
  getPermissionsAsync: jest.fn().mockResolvedValue({ granted: true, canAskAgain: true }),
  requestPermissionsAsync: jest.fn().mockResolvedValue({ granted: true }),
  scheduleNotificationAsync: jest.fn().mockResolvedValue('notification-id'),
  setNotificationChannelAsync: jest.fn(),
}));

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

Then a test asserts how your code talked to the module:

TSX
import * as Notifications from 'expo-notifications';
import { render, screen, fireEvent } from '@testing-library/react-native';
import { ReminderScreen } from './ReminderScreen';

it('schedules a reminder when the user taps Remind me', async () => {
  render(<ReminderScreen />);

  fireEvent.press(screen.getByRole('button', { name: 'Remind me' }));

  expect(Notifications.scheduleNotificationAsync).toHaveBeenCalledWith(
    expect.objectContaining({
      content: expect.objectContaining({ title: 'Reminder' }),
    }),
  );
});

Remember what such a test proves and what it does not. It proves your code calls the notification API with the right arguments. It does not prove a notification appears on a phone, because the real module was replaced. That gap is exactly why a few end-to-end tests exist (see Push Notifications and Native Modules, Expo Modules and Config Plugins). Reset mocks between tests (jest.clearAllMocks() in beforeEach) so one test's calls never leak into the next.

End-to-end tests

End-to-end (E2E) tests install the real app on a simulator or device and drive it like a user. Two tools dominate.

Maestro describes flows in YAML, with no code. It is quick to learn and works for any app that runs on a device:

YAML
# flows/add-note.yaml
appId: com.example.notes
---
- launchApp
- tapOn: "Add note"
- inputText: "Buy milk"
- tapOn: "Save"
- assertVisible: "Buy milk"

You run it with maestro test flows/add-note.yaml. It finds elements by visible text or accessibility identifiers and waits patiently for screens to settle.

Detox is a JavaScript framework built for React Native. It is gray-box: it knows when the app is idle (no pending network calls, animations or timers), so tests are stable without sleeps. It needs more setup and a native test build:

TypeScript
describe('notes', () => {
  beforeAll(async () => {
    await device.launchApp();
  });

  it('adds a note', async () => {
    await element(by.text('Add note')).tap();
    await element(by.id('note-input')).typeText('Buy milk');
    await element(by.text('Save')).tap();
    await expect(element(by.text('Buy milk'))).toBeVisible();
  });
});

Both are slower and more fragile than component tests, so keep them for a short list of critical journeys, and run them on a build machine or in continuous integration before each release. Give important elements stable testID or accessibility labels so flows do not break when copy changes.

Stand-in: a tiny test runner

This TryIt is a toy version of Jest: describe, it, and an expect with a few matchers. It runs a set of tests on the cart logic, and one is written to fail so you can see what a failure report looks like. It is not Jest, but the shape of the API is the same.

A tiny Jest-style test runner

The failure message names the test, the expected value and the received value. That is all you need to find the bug: here the expectation is wrong, because 0 * 4 + 2 * 1 is 2, not 8. A failing test is not always a bug in the code. Sometimes it is a mistake in the test.

Stand-in: a tiny testing library

The last TryIt shows what RNTL does at its core: render a component, find elements the way a user would, trigger a press and check the result. The stand-in renders a web <button> and <p> instead of native views, because there is no native layer here, but the queries and the flow read the same. The tests run once at load and print their results.

getByRole, getByText and fireEvent.press, from scratch

The third test is wrong on purpose, because the counter has no Subtract button. It shows the behavior of getBy: when an element is missing, it throws a message that names what you asked for, so a typo in a test is easy to spot. A real RNTL error also prints the current tree, which helps you see what was actually rendered.

Habits that keep tests useful

  • Test behavior, not implementation. Assert on what the user sees and can do, not on state variables or hook calls. Then refactors do not break tests.
  • One reason to fail. A test with a clear name and one scenario tells you what broke from the title alone.
  • Be careful with snapshots. Huge snapshot files get approved without reading. Use them for small, stable output, never as your main safety net.
  • Mock at the edges. Replace the network, storage, timers and native modules, but keep your own components real.
  • Run tests in continuous integration on every pull request, and keep the suite fast so people actually run it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In React Native Testing Library, which query should you use to assert that an element is NOT on the screen?

    getBy queries throw when nothing matches. queryBy returns null, so you can assert expect(queryByText('Error')).not.toBeOnTheScreen().
  2. 2. A screen loads a user from the network. How do you test the text that appears after loading?

    findBy queries are asynchronous and keep checking until the element appears. Mocking the network keeps the test fast and deterministic.
  3. 3. A test mocks expo-notifications and verifies scheduleNotificationAsync was called. What does that prove?

    The real module is replaced, so the test checks your side of the conversation only. A real device test is needed to see a notification appear.
  4. 4. Where do Maestro and Detox fit in the testing pyramid?

    End-to-end tests are slow and costly, so use a small number for key journeys and rely on unit and component tests for most coverage.

Summary

  • Build a pyramid: many fast Jest unit tests, component tests per screen state with RNTL, and a few E2E flows with Maestro or Detox.
  • Expo projects use the jest-expo preset; extract logic into plain functions so it is cheap to test.
  • Query like a user: getByRole, getByLabelText, getByText; use queryBy for absence and findBy for async content.
  • Test the states a screen can reach: loading, success, error and empty.
  • Mock native modules and the network at the edges, reset mocks between tests, and know that a mock proves only your side of the call.
  • Prefer behavior over implementation, and be cautious with snapshots.

Next, find out why an app is slow or broken in Debugging and Performance Profiling.