Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Testing and Performance

Testing Expo Apps with Jest

Test an Expo app with jest-expo and React Native Testing Library: set up Jest, test pure logic and components, mock native modules, async data and snapshot caution, plus end-to-end options.

Apps break in boring ways: a total is off by one cent, a button stays disabled, an empty list shows a spinner forever. Automated tests catch these before your users do, and they let you refactor without fear. The standard tools in the Expo world are Jest (the test runner), jest-expo (a preset that understands Expo and React Native) and React Native Testing Library (renders components and finds things the way a user would).

What runs on this site. Jest and a React Native renderer are not available in the browser runner, so the real test files are read-only. The runnable stand-ins are a tiny test/expect runner in Node.js and tests of pure logic: the part of an app that is the easiest and most valuable to test.

Setup

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

Run npm test (add --watchAll while developing). Test files end in .test.js/.test.tsx or live in a __tests__ folder.

The anatomy of a test

Jest gives you describe, test (or it) and expect:

JavaScript
import { formatPrice } from './format';

describe('formatPrice', () => {
  test('formats cents as dollars', () => {
    expect(formatPrice(1999)).toBe('$19.99');
  });
  test('rejects negative values', () => {
    expect(() => formatPrice(-1)).toThrow('negative');
  });
});

Each test has three steps: arrange (set up data), act (call the code), assert (check the result). Keep one idea per test, and name it like a sentence.

Node.js A mini test runner (stand-in) testing real logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The failing test prints a clear message: that is what a red Jest run looks like. Never leave a deliberately failing test in a real project.

Testing components

React Native Testing Library renders your component in a test renderer (no phone needed) and gives you queries that mirror what users see: text, labels, roles.

JSX
// Counter.jsx
import { useState } from 'react';
import { Pressable, Text } from 'react-native';

export function Counter() {
  const [n, setN] = useState(0);
  return (
    <Pressable accessibilityRole="button" onPress={() => setN(n + 1)}>
      <Text>Taps: {n}</Text>
    </Pressable>
  );
}
JSX
// Counter.test.jsx
import { render, screen, userEvent } from '@testing-library/react-native';
import { Counter } from './Counter';

test('counts taps', async () => {
  const user = userEvent.setup();
  render(<Counter />);

  expect(screen.getByText('Taps: 0')).toBeOnTheScreen();
  await user.press(screen.getByRole('button'));
  await user.press(screen.getByRole('button'));
  expect(screen.getByText('Taps: 2')).toBeOnTheScreen();
});

Query tips:

  • getBy... throws if nothing matches, queryBy... returns null (use it to assert something is absent), findBy... waits for it to appear (async).
  • Prefer getByRole, getByLabelText and getByText. Use getByTestId only as a last resort. Good queries double as accessibility checks.
  • Test behavior ("tapping Add shows the new item"), not implementation ("state n equals 1").

Async data

Components that fetch data show loading, then content, then maybe an error. Mock the network, then wait with findBy:

JSX
import { render, screen } from '@testing-library/react-native';
import { Profile } from './Profile';

beforeEach(() => {
  global.fetch = jest.fn().mockResolvedValue({
    ok: true,
    json: async () => ({ name: 'Ada' }),
  });
});

test('shows the user name after loading', async () => {
  render(<Profile id={1} />);
  expect(screen.getByText('Loading...')).toBeOnTheScreen();
  expect(await screen.findByText('Ada')).toBeOnTheScreen();
});

test('shows an error message', async () => {
  global.fetch.mockResolvedValue({ ok: false, status: 500, json: async () => ({}) });
  render(<Profile id={1} />);
  expect(await screen.findByText(/failed/i)).toBeOnTheScreen();
});

Always test the failure path as well as the happy path.

Mocking native modules

Native modules (secure store, notifications, camera) do not exist in Node. jest-expo mocks many Expo modules automatically. For others, mock by hand in jest.setup.js:

JavaScript
// jest.setup.js
jest.mock('expo-secure-store', () => {
  const store = new Map();
  return {
    getItemAsync: jest.fn(async (k) => store.get(k) ?? null),
    setItemAsync: jest.fn(async (k, v) => { store.set(k, v); }),
    deleteItemAsync: jest.fn(async (k) => { store.delete(k); }),
  };
});

Better design lowers the need for mocks: wrap each native module in a small file of your own (storage.js), and mock that file. Then your tests do not care which library is underneath.

Making code testable

Logic buried in components is hard to test. Move it into plain functions and custom hooks:

Node.js Test a reducer, not a screen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Snapshots, with care

expect(tree).toMatchSnapshot() saves the rendered output and fails when it changes. It is quick to write and easy to abuse: huge snapshots get approved without reading. Use small, focused snapshots (one icon button, one formatted row) or prefer explicit assertions.

What to test, and how much

flowchart TD
  A["Unit tests: logic, reducers, formatters<br/>many, fast"] --> B["Component tests: screens with mocked network<br/>some"]
  B --> C["End-to-end: Maestro or Detox on a real build<br/>few, slow"]

A pyramid: many cheap tests at the bottom, a few expensive ones on top.

For end-to-end tests that drive the real app, Maestro (simple YAML flows, works well with EAS builds and cloud runs) and Detox are the common choices. Keep them for critical journeys such as sign up, purchase and onboarding. You can run unit and component tests in CI on every push, and run EAS Build workflows for E2E.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Jest preset makes Expo and React Native code testable?

    jest-expo configures transforms, module mapping and mocks for Expo projects.
  2. 2. How do you assert that an element is NOT on the screen?

    queryBy returns null when nothing matches, while getBy throws.
  3. 3. Which query waits for an element to appear?

    findBy returns a promise that resolves when a match shows up, or rejects after a timeout.
  4. 4. What is a good way to avoid mocking a native module everywhere?

    A thin wrapper isolates the dependency, so there is one place to mock.

Summary

  • Use Jest with the jest-expo preset, and React Native Testing Library for components.
  • Test behavior through what users see: text, roles, labels.
  • Use queryBy for absence, findBy for async content, and test error states.
  • Mock the network and native modules; wrap native modules to keep mocks simple.
  • Keep logic in pure functions and reducers, and use E2E tools sparingly for key journeys.

Next: List and render performance