Skip to content

release v7, rename to @testing-library/react-native #468

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jul 30, 2020
Merged
4 changes: 2 additions & 2 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ labels: 'bug report'
<!--
run following command in terminal of your root project and paste the result down

`npx envinfo --npmPackages react,react-native,react-test-renderer,react-native-testing-library`
-->
`npx envinfo --npmPackages react,react-native,react-test-renderer,@testing-library/react-native`
-->
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,4 @@ You can report issues on our [bug tracker](https://github.com/callstack/react-na

## License

By contributing to `react-native-testing-library`, you agree that your contributions will be licensed under its **MIT** license.
By contributing to `@testing-library/react-native`, you agree that your contributions will be licensed under its **MIT** license.
88 changes: 43 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,32 @@
<div align='center'>
<h1>React Native Testing Library</h1>
<img
height="80"
width="80"
alt="owl"
src="https://raw.githubusercontent.com/callstack/react-native-testing-library/master/website/static/img/owl.png"
/>
<h1>React Native Testing Library</h1>

<p>Lightweight React Native testing utilities helping you write better tests with less effort.</P>
<p>Simple and complete React Native testing utilities that encourage good testing practices.</P>
</div>

[![Version][version-badge]][package]
[![PRs Welcome][prs-welcome-badge]][prs-welcome]
[![Chat][chat-badge]][chat]
[![Sponsored by Callstack][callstack-badge]][callstack]

_Appreciation notice: This project is heavily inspired by [react-testing-library](https://github.com/testing-library/react-testing-library). Go check it out and use it to test your web React apps._
> We renamed the `react-native-testing-library` npm package to `@testing-library/react-native`, officially joining the "Testing Library" family 🎉. Read the [migration guide](https://callstack.github.io/react-native-testing-library/docs/migration-v7).

## The problem

You want to write maintainable tests for your React Native components without testing implementation details, but then you're told to use Enzyme, which you learn has no React Native adapter, meaning only shallow rendering is supported. And you want to render deep! But deep rendering may otherwise require jsdom (React Native isn't the web!), while doing deep rendering with `react-test-renderer` is so painful.

You would also like to use the newest React features, but you need to wait for your testing library's abstractions to catch up and it takes a while.

You finally want to approach testing using only best practices, while Enzyme may encourage assertions on implementation details.
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` is a lightweight solution for testing your React Native components. It provides light utility functions on top of `react-test-renderer` letting you always be up to date with latest React features and write any component tests you like. But really not any, it prevents you from testing implementation details because we stand this is a very bad practice.

This library is a replacement for [Enzyme](http://airbnb.io/enzyme/). It is tested to work with Jest, but it should work with other test runners as well.

## Example

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

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

const { getAllByA11yLabel, getByText } = render(
<QuestionsBoard questions={allQuestions} onSubmit={mockFn} />
);

const answerInputs = getAllByA11yLabel('answer input');
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:

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

expect(mockFn).toBeCalledWith({
'1': { q: 'q1', a: 'a1' },
'2': { q: 'q2', a: 'a2' },
});
});
```
> The more your tests resemble the way your software is used, the more confidence they can give you.

You can find the source of `QuestionsBoard` component and this example [here](https://github.com/callstack/react-native-testing-library/blob/master/src/__tests__/questionsBoard.test.js).
This project is inspired by [React Testing Library](https://github.com/testing-library/react-testing-library). Tested to work with Jest, but it should work with other test runners as well.

## Installation

Expand All @@ -67,17 +35,19 @@ Open a Terminal in your project's folder and run:
#### Using `yarn`

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

#### Using `npm`

```sh
npm install --save-dev react-native-testing-library
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.60 (which comes with React >=16.9.0).

### Additional Jest matchers

In order to use addtional React Native-specific jest matchers from [@testing-library/jest-native](https://github.com/testing-library/jest-native) package add it to your project:
Expand Down Expand Up @@ -111,11 +81,38 @@ Note for [Flow](https://flow.org) users – you'll also need to install typings
flow-typed install react-test-renderer
```

As you may have noticed, it's not tied to React Native at all – you can safely use it in your React components if you feel like not interacting directly with DOM.
## Example

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

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

const { getAllByA11yLabel, getByText } = render(
<QuestionsBoard questions={allQuestions} onSubmit={mockFn} />
);

const answerInputs = getAllByA11yLabel('answer input');

fireEvent.changeText(answerInputs[0], 'a1');
fireEvent.changeText(answerInputs[1], 'a2');
fireEvent.press(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](https://github.com/callstack/react-native-testing-library/blob/master/src/__tests__/questionsBoard.test.js).

## API / Usage

The [public API](https://callstack.github.io/react-native-testing-library/docs/api) of `react-native-testing-library` is focused around these essential methods:
The [public API](https://callstack.github.io/react-native-testing-library/docs/api) of `@testing-library/react-native` is focused around these essential methods:

- [`render`](https://callstack.github.io/react-native-testing-library/docs/api#render) – deeply renders given React element and returns helpers to query the output components.
- [`fireEvent`](https://callstack.github.io/react-native-testing-library/docs/api#fireevent) - invokes named event handler on the element.
Expand All @@ -125,6 +122,7 @@ The [public API](https://callstack.github.io/react-native-testing-library/docs/a

## Migration Guides

- [Migration to 7.0](https://callstack.github.io/react-native-testing-library/docs/migration-v7)
- [Migration to 2.0](https://callstack.github.io/react-native-testing-library/docs/migration-v2)

## Related External Resources
Expand All @@ -142,8 +140,8 @@ Supported and used by [Rally Health](https://www.rallyhealth.com/careers-home).

<!-- badges -->

[version-badge]: https://img.shields.io/npm/v/react-native-testing-library.svg?style=flat-square
[package]: https://www.npmjs.com/package/react-native-testing-library
[version-badge]: https://img.shields.io/npm/v/@testing-library/react-native.svg?style=flat-square
[package]: https://www.npmjs.com/package/@testing-library/react-native
[prs-welcome-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[prs-welcome]: http://makeapullrequest.com
[chat-badge]: https://img.shields.io/discord/426714625279524876.svg?style=flat-square&colorB=758ED3
Expand Down
4 changes: 2 additions & 2 deletions examples/reactnavigation/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-navigation-example",
"description": "Testing react-navigation with react-native-testing-library",
"description": "Testing React Navigation with RNTL",
"version": "0.0.1",
"private": true,
"scripts": {
Expand All @@ -24,7 +24,7 @@
"babel-jest": "^25.4.0",
"jest": "^25.4.0",
"metro-react-native-babel-preset": "^0.59.0",
"react-native-testing-library": "^1.13.0",
"@testing-library/react-native": "^7.0.0-rc.0",
"react-test-renderer": "^16.13.1"
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { render, fireEvent } from 'react-native-testing-library';
import { render, fireEvent } from '@testing-library/react-native';

import AppNavigator from '../AppNavigator';

Expand Down
6 changes: 3 additions & 3 deletions examples/redux/components/AddTodo.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { Provider } from 'react-redux';
import { fireEvent, render } from 'react-native-testing-library';
import { fireEvent, render } from '@testing-library/react-native';
import configureStore from '../store';
import AddTodo from './AddTodo';

Expand All @@ -14,9 +14,9 @@ describe('Application test', () => {
</Provider>
);

const { getByPlaceholder, getByText } = render(component);
const { getByPlaceholderText, getByText } = render(component);

const input = getByPlaceholder(/repository/i);
const input = getByPlaceholderText(/repository/i);
expect(input).toBeTruthy();

const textToEnter = 'This is a random element';
Expand Down
2 changes: 1 addition & 1 deletion examples/redux/components/TodoList.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { Provider } from 'react-redux';
import { fireEvent, render } from 'react-native-testing-library';
import { fireEvent, render } from '@testing-library/react-native';
import configureStore from '../store';
import TodoList from './TodoList';

Expand Down
2 changes: 1 addition & 1 deletion examples/redux/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"babel-jest": "~25.2.6",
"jest": "~25.2.6",
"metro-react-native-babel-preset": "^0.59.0",
"react-native-testing-library": "^1.13.2",
"@testing-library/react-native": "^7.0.0-rc.0",
"react-test-renderer": "~16.9.0"
},
"private": true,
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "react-native-testing-library",
"version": "2.2.0",
"description": "Simple React Native testing utilities helping you write better tests with less effort",
"name": "@testing-library/react-native",
"version": "7.0.0-rc.0",
"description": "Simple and complete React Native testing utilities that encourage good testing practices.",
"main": "build/index.js",
"typings": "./typings/index.d.ts",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion pure.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
// makes it so people can import from 'react-native-testing-library/pure'
// makes it so people can import from '@testing-library/react-native/pure'
module.exports = require('./build/pure');
16 changes: 8 additions & 8 deletions src/__tests__/findByApi.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ test('findBy queries work asynchronously', async () => {
findAllByTestId,
findByText,
findAllByText,
findByPlaceholder,
findAllByPlaceholder,
findByPlaceholderText,
findAllByPlaceholderText,
findByDisplayValue,
findAllByDisplayValue,
} = render(<View />);
Expand All @@ -21,10 +21,10 @@ test('findBy queries work asynchronously', async () => {
await expect(findByText('Some Text', options)).rejects.toBeTruthy();
await expect(findAllByText('Some Text', options)).rejects.toBeTruthy();
await expect(
findByPlaceholder('Placeholder Text', options)
findByPlaceholderText('Placeholder Text', options)
).rejects.toBeTruthy();
await expect(
findAllByPlaceholder('Placeholder Text', options)
findAllByPlaceholderText('Placeholder Text', options)
).rejects.toBeTruthy();
await expect(
findByDisplayValue('Display Value', options)
Expand All @@ -49,10 +49,10 @@ test('findBy queries work asynchronously', async () => {
await expect(findAllByTestId('aTestId')).resolves.toHaveLength(1);
await expect(findByText('Some Text')).resolves.toBeTruthy();
await expect(findAllByText('Some Text')).resolves.toHaveLength(1);
await expect(findByPlaceholder('Placeholder Text')).resolves.toBeTruthy();
await expect(findAllByPlaceholder('Placeholder Text')).resolves.toHaveLength(
1
);
await expect(findByPlaceholderText('Placeholder Text')).resolves.toBeTruthy();
await expect(
findAllByPlaceholderText('Placeholder Text')
).resolves.toHaveLength(1);
await expect(findByDisplayValue('Display Value')).resolves.toBeTruthy();
await expect(findAllByDisplayValue('Display Value')).resolves.toHaveLength(1);
}, 20000);
86 changes: 84 additions & 2 deletions src/__tests__/fireEvent.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React from 'react';
import {
View,
TouchableOpacity,
Pressable,
Text,
ScrollView,
TextInput,
Expand Down Expand Up @@ -123,7 +124,7 @@ test('fireEvent.changeText', () => {
const onChangeTextMock = jest.fn();
const CHANGE_TEXT = 'content';

const { getByPlaceholder } = render(
const { getByPlaceholderText } = render(
<View>
<TextInput
placeholder="Customer placeholder"
Expand All @@ -132,7 +133,10 @@ test('fireEvent.changeText', () => {
</View>
);

fireEvent.changeText(getByPlaceholder('Customer placeholder'), CHANGE_TEXT);
fireEvent.changeText(
getByPlaceholderText('Customer placeholder'),
CHANGE_TEXT
);

expect(onChangeTextMock).toHaveBeenCalledWith(CHANGE_TEXT);
});
Expand Down Expand Up @@ -160,3 +164,81 @@ test('event with multiple handler parameters', () => {

expect(handlePress).toHaveBeenCalledWith('param1', 'param2');
});

test('should not fire on disabled TouchableOpacity', () => {
const handlePress = jest.fn();
const screen = render(
<TouchableOpacity onPress={handlePress} disabled={true}>
<Text>Trigger</Text>
</TouchableOpacity>
);

expect(() => fireEvent.press(screen.getByText('Trigger'))).toThrow(
'No handler function found for event: "press"'
);
expect(handlePress).not.toHaveBeenCalled();
});

test('should not fire on disabled Pressable', () => {
const handlePress = jest.fn();
const screen = render(
<Pressable onPress={handlePress} disabled={true}>
<Text>Trigger</Text>
</Pressable>
);

expect(() => fireEvent.press(screen.getByText('Trigger'))).toThrow(
'No handler function found for event: "press"'
);
expect(handlePress).not.toHaveBeenCalled();
});

test('should pass event up on disabled TouchableOpacity', () => {
const handleInnerPress = jest.fn();
const handleOuterPress = jest.fn();
const screen = render(
<TouchableOpacity onPress={handleOuterPress}>
<TouchableOpacity onPress={handleInnerPress} disabled={true}>
<Text>Inner Trigger</Text>
</TouchableOpacity>
</TouchableOpacity>
);

fireEvent.press(screen.getByText('Inner Trigger'));
expect(handleInnerPress).not.toHaveBeenCalled();
expect(handleOuterPress).toHaveBeenCalledTimes(1);
});

test('should pass event up on disabled Pressable', () => {
const handleInnerPress = jest.fn();
const handleOuterPress = jest.fn();
const screen = render(
<Pressable onPress={handleOuterPress}>
<Pressable onPress={handleInnerPress} disabled={true}>
<Text>Inner Trigger</Text>
</Pressable>
</Pressable>
);

fireEvent.press(screen.getByText('Inner Trigger'));
expect(handleInnerPress).not.toHaveBeenCalled();
expect(handleOuterPress).toHaveBeenCalledTimes(1);
});

const TestComponent = ({ onPress }) => {
return (
<TouchableOpacity onPress={onPress}>
<Text>Trigger Test</Text>
</TouchableOpacity>
);
};

test('is not fooled by non-native disabled prop', () => {
const handlePress = jest.fn();
const screen = render(
<TestComponent onPress={handlePress} disabled={true} />
);

fireEvent.press(screen.getByText('Trigger Test'));
expect(handlePress).toHaveBeenCalledTimes(1);
});
Loading