Files
callstack__react-native-tes…/README.md
T

322 lines
11 KiB
Markdown
Raw Normal View History

2018-10-01 18:15:56 +02:00
# react-native-testing-library
2018-10-06 19:40:29 +02:00
Simple React Native testing utilities helping you write better tests with less effort
2018-10-06 19:39:44 +02:00
[![Build Status][build-badge]][build]
[![Version][version-badge]][package]
[![MIT License][license-badge]][license]
[![PRs Welcome][prs-welcome-badge]][prs-welcome]
[![Chat][chat-badge]][chat]
Update dependencies to enable Greenkeeper 🌴 (#14) Let’s get started with automated dependency management for react-native-testing-library :muscle: 🔒 Greenkeeper has found a `yarn.lock` file in this repository. Greenkeeper supports lockfile updates for public packages. If you use private packages in your repository, please use [greenkeeper-lockfile](https://github.com/greenkeeperio/greenkeeper-lockfile) to make sure these can get updated as well. This pull request **updates all your dependencies to their latest version**. Having them all up to date really is the best starting point for keeping up with new releases. Greenkeeper will look out for further dependency updates and make sure to handle them in isolation and in real-time, but only after **you merge this pull request**. **Important: Greenkeeper will only start watching this repository’s dependency updates after you merge this initial pull request**. --- <details> <summary>🏷 How to check the status of this repository</summary> Greenkeeper adds a badge to your README which indicates the status of this repository. This is what your badge looks like right now :point_right: ![Greenkeeper badge](https://badges.greenkeeper.io/callstack/react-native-testing-library.svg) </details> <details> <summary>🙈 How to ignore certain dependencies</summary> You may have good reasons for not wanting to update to a certain dependency right now. In this case, you can [change the dependency’s version string in the `package.json` file back to whatever you prefer](https://github.com/callstack/react-native-testing-library/edit/greenkeeper/initial/package.json). To make sure Greenkeeper doesn’t nag you again on the next update, add a `greenkeeper.ignore` field to your `package.json`, containing a list of dependencies you don’t want to update. ```js // package.json { … "greenkeeper": { "ignore": [ "package-names", "you-want-me-to-ignore" ] } } ``` </details> <details> <summary>👩‍💻 How to update this pull request</summary> ```bash # Change into your repository’s directory git fetch --all git checkout greenkeeper/initial npm install-test # Adapt your code until everything works again git commit -m 'chore: adapt code to updated dependencies' git push https://github.com/callstack/react-native-testing-library.git greenkeeper/initial ``` </details> <details> <summary>✨ How do dependency updates work with Greenkeeper?</summary> After you merge this pull request, **Greenkeeper will create a new branch whenever a dependency is updated**, with the new version applied. The branch creation should trigger your testing services and check whether your code still works with the new dependency version. Depending on the the results of these tests Greenkeeper will try to open meaningful and helpful pull requests and issues, so your dependencies remain working and up-to-date. ```diff - "underscore": "^1.6.0" + "underscore": "^1.7.0" ``` The above example shows an in-range update. `1.7.0` is included in the old `^1.6.0` range, because of the [caret `^` character ](https://docs.npmjs.com/misc/semver#ranges). When the test services report success Greenkeeper will silently delete the branch again, because no action needs to be taken – everything is fine. However, should the tests fail, Greenkeeper will create an issue to inform you about the problem immediately. This way, you’ll never be surprised by a dependency breaking your code. As long as everything still works, Greenkeeper will stay out of your way, and as soon as something goes wrong, you’ll be the first to know. ```diff - "lodash": "^3.0.0" + "lodash": "^4.0.0" ``` In this example, the new version `4.0.0` is _not_ included in the old `^3.0.0` range. For version updates like these – let’s call them “out of range” updates – you’ll receive a pull request. This means that **you no longer need to check for new versions manually** – Greenkeeper will keep you up to date automatically. These pull requests not only serve as reminders to update: If you have solid tests and good coverage, and the pull requests passes those tests, you can very likely just merge it and release a new version of your software straight away :shipit: To get a better idea of which ranges apply to which releases, check out the extremely useful [semver calculator](https://semver.npmjs.com/) provided by npm. </details> <details> <summary>FAQ and help</summary> There is a collection of [frequently asked questions](https://greenkeeper.io/faq.html). If those don’t help, you can always [ask the humans behind Greenkeeper](https://github.com/greenkeeperio/greenkeeper/issues/new). </details> --- Good luck with your project and see you soon :sparkles: Your [Greenkeeper](https://greenkeeper.io) bot :palm_tree:
2018-10-07 11:40:29 +02:00
[![Greenkeeper badge](https://badges.greenkeeper.io/callstack/react-native-testing-library.svg)](https://greenkeeper.io/)
2018-10-06 19:39:44 +02:00
2018-10-04 23:44:59 +02:00
_Appreciation notice: This project is heavily inspired by [react-testing-library](https://github.com/kentcdodds/react-testing-library). Go check it out and use it to test your web React apps._
2018-10-03 19:15:36 +02:00
## 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 only supports shallow rendering in React Native environment. And you want to render deep! But doing so 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.
## 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, be it shallow or deeply rendered ones. 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/).
## Example
```jsx
import { render, fireEvent } from 'react-native-testing-library';
import { QuestionsBoard } from '../QuestionsBoard';
2018-10-04 09:17:15 +02:00
function setAnswer(question, answer) {
fireEvent.changeText(question, answer);
}
test('should verify two questions', () => {
const { getAllByName, getByText } = render(<QuestionsBoard {...props} />);
2018-10-04 09:17:15 +02:00
const allQuestions = getAllByName('Question');
2018-10-04 09:17:15 +02:00
setAnswer(allQuestions[0], 'a1');
setAnswer(allQuestions[1], 'a2');
fireEvent.press(getByText('submit'));
expect(props.verifyQuestions).toBeCalledWith({
'1': { q: 'q1', a: 'a1' },
'2': { q: 'q2', a: 'a2' },
});
});
```
2018-10-03 19:15:36 +02:00
## Installation
Open a Terminal in your project's folder and run:
```sh
yarn add --dev react-native-testing-library
2018-10-03 19:15:36 +02:00
```
This library has a peerDependencies listing for `react-test-renderer`, `pretty-format` and, of course, `react`. Make sure to install them too!
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.
2018-10-03 19:15:36 +02:00
## Usage
## `render`
Defined as:
```jsx
function render(
component: React.Element<*>,
options?: {
/* You won't often use this, but it's helpful when testing refs */
createNodeMock: (element: React.Element<*>) => any,
}
): RenderResult {}
```
Deeply render given React element and returns helpers to query the output. For convenience it also returns `react-test-renderer`'s `instance` and `renderer` objects, in case you need more control.
2018-10-03 19:15:36 +02:00
```jsx
import { render } from 'react-native-testing-library';
const { getByTestId, getByName /*...*/ } = render(<Component />);
```
Returns a `RenderResult` object with following properties:
### `getByTestId: (testID: string)`
A method returning a `ReactTestInstance` with matching `testID` prop. Throws when no matches.
_Note: most methods like this one return a [`ReactTestInstance`](https://reactjs.org/docs/test-renderer.html#testinstance) with following properties that you may be interested in:_
```jsx
type ReactTestInstance = {
type: string | Function,
props: { [propName: string]: any },
parent: null | ReactTestInstance,
children: Array<ReactTestInstance | string>,
};
2018-10-03 19:15:36 +02:00
```
### `getByName: (name: string | React.ComponentType<*>)`
A method returning a `ReactTestInstance` with matching name – may be a string or React Element. Throws when no matches.
### `getAllByName: (name: string | React.ComponentType<*>)`
A method returning an array of `ReactTestInstance`s with matching name – may be a string or React Element.
### `getByText: (text: string | RegExp)`
A method returning a `ReactTestInstance` with matching text – may be a string or regular expression. Throws when no matches.
### `getAllByText: (text: string | RegExp)`
A method returning an array of `ReactTestInstance`s with matching text – may be a string or regular expression.
### `getByProps: (props: { [propName: string]: any })`
A method returning a `ReactTestInstance` with matching props object. Throws when no matches.
### `getAllByProps: (props: { [propName: string]: any })`
A method returning an array of `ReactTestInstance`s with matching props object.
### `update: (element: React.Element<*>) => void`
Re-render the in-memory tree with a new root element. This simulates a React update at the root. If the new element has the same type and key as the previous element, the tree will be updated; otherwise, it will re-mount a new tree.
### `unmount: () => void`
Unmount the in-memory tree, triggering the appropriate lifecycle events
When using React context providers, like Redux Provider, you'll likely want to wrap rendered component with them. In such cases it's convenient to create your custom `render` method. [Follow this great guide on how to set this up](https://github.com/kentcdodds/react-testing-library#custom-render).
2018-10-03 19:15:36 +02:00
## `shallow`
Shallowly render given React copmonent. Since it doesn't return helpers to query the output, it's mostly adviced to used for snapshot testing (short snapshots are best for code reviewers).
2018-10-03 19:15:36 +02:00
```jsx
import { shallow } from 'react-native-testing-library';
test('Component has a structure', () => {
const { output } = shallow(<Component />);
expect(output).toMatchSnapshot();
2018-10-03 19:15:36 +02:00
});
```
## `FireEvent API`
### `fireEvent: (element: ReactTestInstance, eventName: string, data?: *) => void`
Invokes named event handler on the element or parent element in the tree.
```jsx
import { View } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';
import { MyComponent } from './MyComponent';
const onEventMock = jest.fn();
const { getByTestId } = render(
<MyComponent testID="custom" onMyCustomEvent={onEventMock} />
);
fireEvent(getByTestId('custom'), 'myCustomEvent');
```
### `fireEvent.press: (element: ReactTestInstance) => void`
Invokes `press` event handler on the element or parent element in the tree.
```jsx
import { View, Text, TouchableOpacity } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';
const onPressMock = jest.fn();
const { getByTestId } = render(
<View>
<TouchableOpacity onPress={onPressMock} testID="button">
<Text>Press me</Text>
</TouchableOpacity>
</View>
);
fireEvent.press(getByTestId('button'));
```
### `fireEvent.doublePress: (element: ReactTestInstance) => void`
Invokes `doublePress` event handler on the element or parent element in the tree.
```jsx
import { TouchableOpacity, Text } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';
const onDoublePressMock = jest.fn();
const { getByTestId } = render(
<TouchableOpacity onDoublePress={onDoublePressMock}>
<Text testID="button-text">Click me</Text>
</TouchableOpacity>
);
fireEvent.doublePress(getByTestId('button-text'));
```
### `fireEvent.changeText: (element: ReactTestInstance, data?: *) => void`
Invokes `changeText` event handler on the element or parent element in the tree.
```jsx
import { View, TextInput } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';
const onChangeTextMock = jest.fn();
const CHANGE_TEXT = 'content';
const { getByTestId } = render(
<View>
<TextInput testID="text-input" onChangeText={onChangeTextMock} />
</View>
);
fireEvent.changeText(getByTestId('text-input'), CHANGE_TEXT);
```
### `fireEvent.scroll: (element: ReactTestInstance, data?: *) => void`
Invokes `scroll` event handler on the element or parent element in the tree.
```jsx
import { ScrollView, TextInput } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';
const onScrollMock = jest.fn();
const eventData = {
nativeEvent: {
contentOffset: {
y: 200,
},
},
};
const { getByTestId } = render(
<ScrollView testID="scroll-view" onScroll={onScrollMock}>
<Text>XD</Text>
</ScrollView>
);
fireEvent.scroll(getByTestId('scroll-view'), eventData);
```
2018-10-03 19:15:36 +02:00
## `debug`
Log prettified shallowly rendered component or test instance (just like snapshot) to stdout.
```jsx
import { debug } from 'react-native-testing-library';
debug(<Component />);
// console.log:
// <View>
// <Text>Component</Text>
// </View>
```
## `flushMicrotasksQueue`
Wait for microtasks queue to flush. Useful if you want to wait for some promises with `async/await`.
```jsx
import { flushMicrotasksQueue, render } from 'react-native-testing-library';
test('fetch data', async () => {
const { getByText } = render(<FetchData />);
getByText('fetch');
await flushMicrotasksQueue();
expect(getByText('fetch').props.title).toBe('loaded');
});
```
2018-10-06 19:39:44 +02:00
## `query` APIs
Each of the get APIs listed in the render section above have a complimentary query API. The get APIs will throw errors if a proper node cannot be found. This is normally the desired effect. However, if you want to make an assertion that an element is not present in the hierarchy, then you can use the query API instead:
```jsx
import { render } from 'react-native-testing-library';
const { queryByText } = render(<Form />);
const submitButton = queryByText('submit');
expect(submitButton).toBeNull(); // it doesn't exist
```
## `queryAll` APIs
Each of the query APIs have a corresponding queryAll version that always returns an Array of matching nodes. getAll is the same but throws when the array has a length of 0.
```jsx
import { render } from 'react-native-testing-library';
const { queryAllByText } = render(<Forms />);
const submitButtons = queryAllByText('submit');
expect(submitButtons).toHaveLength(3); // expect 3 elements
```
2018-10-06 19:39:44 +02:00
<!-- badges -->
2018-10-06 19:39:44 +02:00
[build-badge]: https://img.shields.io/circleci/project/github/callstack/react-native-testing-library/master.svg?style=flat-square
[build]: https://circleci.com/gh/callstack/react-native-testing-library
[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
[license-badge]: https://img.shields.io/npm/l/react-native-testing-library.svg?style=flat-square
[license]: https://opensource.org/licenses/MIT
[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
[chat]: https://discord.gg/QbGezWe