/react-native-testing-library

🦉 Simple and complete React Native testing utilities that encourage good testing practices.

Primary LanguageTypeScriptMIT LicenseMIT

React Native Testing Library

owl

Simple and complete React Native testing utilities that encourage good testing practices.

Version PRs Welcome Chat Sponsored by Callstack

The problem

You want to write maintainable tests for your React Native components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended. As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.

This solution

The React Native Testing Library (RNTL) is a lightweight solution for testing React Native components. It provides light utility functions on top of react-test-renderer, in a way that encourages better testing practices. Its primary guiding principle is:

The more your tests resemble the way your software is used, the more confidence they can give you.

This project is inspired by React Testing Library. Tested to work with Jest, but it should work with other test runners as well.

Installation

Open a Terminal in your project's folder and run:

Using yarn

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

Using npm

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

This library has a peerDependencies listing for react-test-renderer and, of course, react. Make sure to install them too!

In order to properly use helpers for async tests (findBy queries and waitFor) you need at least React >=16.9.0 (featuring async act) or React Native >=0.61 (which comes with React >=16.9.0).

Additional Jest matchers

In order to use additional React Native-specific jest matchers from @testing-library/jest-native package add it to your project:

Using yarn

yarn add --dev @testing-library/jest-native

Using npm

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

Then automatically add it to your jest tests by using setupFilesAfterEnv option in your Jest configuration (it's usually located either in package.json under "jest" key or in a jest.config.json file):

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

Custom Jest Preset

important if you use "modern" Fake Timers

We generally advise to use the "react-native" preset when testing with this library. However, if you use "modern" Fake Timers (default since Jest 27), you'll need to apply our custom Jest preset or awaiting promises, like waitFor, will timeout.

This is a known issue. It happens because React Native's Jest preset overrides native Promise. Our preset restores it to defaults, which is not a problem in most apps out there.

Here's how you apply a custom preset in your Jest config:

{
  "preset": "@testing-library/react-native"
}

If this doesn't work for you, please fall back to using "legacy" fake timers.

Flow

Note for Flow users – you'll also need to install typings for react-test-renderer:

flow-typed install react-test-renderer

Example

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

test('form submits two answers', () => {
  const allQuestions = ['q1', 'q2'];
  const mockFn = jest.fn();

  render(<QuestionsBoard questions={allQuestions} onSubmit={mockFn} />);

  const answerInputs = screen.getAllByLabelText('answer input');

  fireEvent.changeText(answerInputs[0], 'a1');
  fireEvent.changeText(answerInputs[1], 'a2');
  fireEvent.press(screen.getByText('Submit'));

  expect(mockFn).toBeCalledWith({
    '1': { q: 'q1', a: 'a1' },
    '2': { q: 'q2', a: 'a2' },
  });
});

You can find the source of QuestionsBoard component and this example here.

API / Usage

The public API of @testing-library/react-native is focused around these essential methods:

  • render – deeply renders given React element and returns helpers to query the output components.
  • fireEvent - invokes named event handler on the element.
  • waitFor - waits for non-deterministic periods of time until queried element is added or times out.
  • waitForElementToBeRemoved - waits for non-deterministic periods of time until queried element is removed or times out.
  • within - creates a queries object scoped for given element.

Migration Guides

Troubleshooting

Related External Resources

Made with ❤️ at Callstack

React Native Testing Library is an open source project and will always remain free to use. If you think it's cool, please star it 🌟. Callstack is a group of React and React Native geeks, contact us at hello@callstack.com if you need any help with these or just want to say hi!

Like the project? ⚛️ Join the team who does amazing stuff for clients and drives React Native Open Source! 🔥


Supported and used by Rally Health.