2018-12-11 12:58:37 -06:00
---
id: api
title: API
---
2018-11-23 15:03:22 +01:00
2020-07-28 11:50:49 +02:00
This page gathers public API of React Native Testing Library along with usage examples.
2018-11-23 15:03:22 +01:00
2019-04-14 10:09:46 +02:00
## `render`
2019-01-15 14:25:28 -02:00
- [`Example code` ](https://github.com/callstack/react-native-testing-library/blob/master/src/__tests__/render.test.js )
2018-11-23 15:03:22 +01:00
Defined as:
``` jsx
function render (
2018-11-28 12:49:15 +01:00
component : React . Element < any > ,
2018-11-23 15:03:22 +01:00
options ? : {
2019-05-28 13:31:48 -07:00
/* A React Component that renders `component` as children */
wrapper ? : React . ComponentType < any > ,
2018-11-23 15:03:22 +01:00
/* You won't often use this, but it's helpful when testing refs */
2018-11-28 12:49:15 +01:00
createNodeMock : ( element : React . Element < any > ) => any ,
2018-11-23 15:03:22 +01:00
}
) : RenderResult { }
```
Deeply renders given React element and returns helpers to query the output components structure.
``` jsx
2020-07-28 11:50:49 +02:00
import { render } from '@testing-library/react-native' ;
2019-06-11 13:32:26 +02:00
import { QuestionsBoard } from '../QuestionsBoard' ;
2018-11-23 15:03:22 +01:00
2019-06-11 13:32:26 +02:00
test ( 'should verify two questions' , ( ) => {
const { queryAllByA11yRole } = render ( < QuestionsBoard { ...props } / > ) ;
const allQuestions = queryAllByA11yRole ( 'header' ) ;
expect ( allQuestions ) . toHaveLength ( 2 ) ;
} ) ;
2018-11-23 15:03:22 +01:00
```
2019-06-11 13:32:26 +02:00
> 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://testing-library.com/docs/react-testing-library/setup#custom-render).
2019-06-11 13:07:00 +02:00
The `render` method returns a `RenderResult` object that has a few properties:
### `...queries`
The most important feature of `render` is providing a set of helpful queries that allow you to find certain elements in the view hierarchy.
See [Queries ](./Queries.md ) for a complete list.
#### Example
``` jsx
2020-07-28 11:50:49 +02:00
import { render } from '@testing-library/react-native' ;
2019-06-11 13:32:26 +02:00
const { getByText , queryByA11yStates } = render ( < Component / > ) ;
2019-06-11 13:07:00 +02:00
```
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
### `update`
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
_ Also available under `rerender` alias _
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
``` ts
update ( element : React.Element < any > ) : void
rerender ( element : React.Element < any > ) : void
2018-11-23 15:03:22 +01:00
```
2019-04-01 16:39:01 +02:00
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. This is useful when testing for `componentDidUpdate` behavior, by passing updated props to the component.
[Example code ](https://github.com/callstack/react-native-testing-library/blob/f96d782d26dd4815dbfd01de6ef7a647efd1f693/src/__tests__/act.test.js#L31-L37 )
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
### `unmount`
``` ts
unmount ( ) : void
```
2018-11-23 15:03:22 +01:00
2020-05-20 07:33:28 -04:00
Unmount the in-memory tree, triggering the appropriate lifecycle events.
:::note
Usually you should not need to call `unmount` as it is done automatically if your test runner supports `afterEach` hook (like Jest, mocha, Jasmine).
:::
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
### `debug`
``` ts
debug ( message? : string ) : void
```
2018-11-23 15:03:22 +01:00
2020-08-12 18:48:37 +02:00
Pretty prints deeply rendered component passed to `render` with optional message on top.
2018-11-23 15:03:22 +01:00
``` jsx
const { debug } = render ( < Component / > ) ;
debug ( 'optional message' ) ;
```
logs optional message and colored JSX:
``` jsx
optional message
2020-08-12 18:48:37 +02:00
< View
2018-11-23 15:03:22 +01:00
onPress = { [ Function bound fn ] }
>
< Text > Press me < / Text >
2020-08-12 18:48:37 +02:00
< / View >
2018-11-23 15:03:22 +01:00
```
2019-04-14 16:12:50 +02:00
#### `debug.shallow`
2018-11-23 15:03:22 +01:00
2020-08-12 18:48:37 +02:00
Pretty prints shallowly rendered component passed to `render` with optional message on top.
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
### `toJSON`
``` ts
toJSON ( ) : ReactTestRendererJSON | null
```
2018-11-23 15:03:22 +01:00
Get the rendered component JSON representation, e.g. for snapshot testing.
2020-10-21 12:26:01 +02:00
### `container`
``` ts
container : ReactTestInstance ;
```
A reference to the rendered root element.
2019-12-09 05:41:48 -05:00
## `cleanup`
``` ts
2020-05-08 14:37:28 +00:00
const cleanup : ( ) = > void ;
2019-12-09 05:41:48 -05:00
```
Unmounts React trees that were mounted with `render` .
2020-05-20 07:33:28 -04:00
:::info
Please note that this is done automatically if the testing framework you're using supports the `afterEach` global (like mocha, Jest, and Jasmine). If not, you will need to do manual cleanups after each test.
:::
2019-12-09 05:41:48 -05:00
For example, if you're using the `jest` testing framework, then you would need to use the `afterEach` hook like so:
``` jsx
2020-07-28 11:50:49 +02:00
import { cleanup , render } from '@testing-library/react-native/pure' ;
2020-05-08 14:37:28 +00:00
import { View } from 'react-native' ;
2019-12-09 05:41:48 -05:00
2020-05-08 14:37:28 +00:00
afterEach ( cleanup ) ;
2019-12-09 05:41:48 -05:00
it ( 'renders a view' , ( ) => {
2020-05-08 14:37:28 +00:00
render ( < View / > ) ;
2019-12-09 05:41:48 -05:00
// ...
2020-05-08 14:37:28 +00:00
} ) ;
2019-12-09 05:41:48 -05:00
```
The `afterEach(cleanup)` call also works in `describe` blocks:
``` jsx
describe ( 'when logged in' , ( ) => {
2020-05-08 14:37:28 +00:00
afterEach ( cleanup ) ;
2019-12-09 05:41:48 -05:00
it ( 'renders the user' , ( ) => {
2020-05-08 14:37:28 +00:00
render ( < SiteHeader / > ) ;
2019-12-09 05:41:48 -05:00
// ...
} ) ;
2020-05-08 14:37:28 +00:00
} ) ;
2019-12-09 05:41:48 -05:00
```
Failing to call `cleanup` when you've called `render` could result in a memory leak and tests which are not "idempotent" (which can lead to difficult to debug errors in your tests).
The alternative to `cleanup` is balancing every `render` with an `unmount` method call.
2018-11-23 15:03:22 +01:00
## `fireEvent`
2019-04-14 16:12:50 +02:00
``` ts
2019-07-16 16:19:59 +02:00
fireEvent ( element : ReactTestInstance , eventName : string , . . . data : Array < any > ) : void
2019-04-14 16:12:50 +02:00
```
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
Fires native-like event with data.
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
Invokes a given event handler (whether native or custom) on the element, bubbling to the root of the rendered tree.
2018-11-23 15:03:22 +01:00
``` jsx
2020-07-28 11:50:49 +02:00
import { render , fireEvent } from '@testing-library/react-native' ;
2018-11-23 15:03:22 +01:00
2019-04-14 16:12:50 +02:00
test ( 'fire changeText event' , ( ) => {
const onEventMock = jest . fn ( ) ;
2020-07-24 22:53:34 +02:00
const { getByPlaceholderText } = render (
2020-05-08 14:37:28 +00:00
// MyComponent renders TextInput which has a placeholder 'Enter details'
// and with `onChangeText` bound to handleChangeText
< MyComponent handleChangeText = { onEventMock } / >
2019-04-14 16:12:50 +02:00
) ;
2018-11-23 15:03:22 +01:00
2020-07-24 22:53:34 +02:00
fireEvent ( getByPlaceholderText ( 'change' ) , 'onChangeText' , 'ab' ) ;
2019-04-14 16:12:50 +02:00
expect ( onEventMock ) . toHaveBeenCalledWith ( 'ab' ) ;
} ) ;
2018-11-23 15:03:22 +01:00
```
2020-07-28 15:11:28 +02:00
:::note
Please note that from version `7.0` `fireEvent` performs checks that should prevent events firing on disabled elements.
:::
2018-12-28 05:51:35 -05:00
An example using `fireEvent` with native events that aren't already aliased by the `fireEvent` api.
``` jsx
import { TextInput , View } from 'react-native' ;
2020-07-28 11:50:49 +02:00
import { fireEvent , render } from '@testing-library/react-native' ;
2018-12-28 05:51:35 -05:00
const onBlurMock = jest . fn ( ) ;
2020-07-24 22:53:34 +02:00
const { getByPlaceholderText } = render (
2018-12-28 05:51:35 -05:00
< View >
< TextInput placeholder = "my placeholder" onBlur = { onBlurMock } / >
< / View >
) ;
2019-04-14 16:12:50 +02:00
// you can omit the `on` prefix
2020-07-24 22:53:34 +02:00
fireEvent ( getByPlaceholderText ( 'my placeholder' ) , 'blur' ) ;
2018-12-28 05:51:35 -05:00
```
2019-04-14 16:12:50 +02:00
## `fireEvent[eventName]`
``` ts
2019-07-16 16:19:59 +02:00
fireEvent [ eventName ] ( element : ReactTestInstance , . . . data : Array < any > ) : void
2019-04-14 16:12:50 +02:00
```
Convenience methods for common events like: `press` , `changeText` , `scroll` .
2018-11-23 15:03:22 +01:00
### `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' ;
2020-07-28 11:50:49 +02:00
import { render , fireEvent } from '@testing-library/react-native' ;
2018-11-23 15:03:22 +01:00
const onPressMock = jest . fn ( ) ;
2020-05-08 14:37:28 +00:00
const { getByText } = render (
2018-11-23 15:03:22 +01:00
< View >
2020-05-08 14:37:28 +00:00
< TouchableOpacity onPress = { onPressMock } >
2018-11-23 15:03:22 +01:00
< Text > Press me < / Text >
< / TouchableOpacity >
< / View >
) ;
2020-05-08 14:37:28 +00:00
fireEvent . press ( getByText ( 'Press me' ) ) ;
expect ( onPressMock ) . toHaveBeenCalled ( ) ;
2018-11-23 15:03:22 +01:00
```
2019-07-16 16:19:59 +02:00
### `fireEvent.changeText: (element: ReactTestInstance, ...data: Array<any>) => void`
2018-11-23 15:03:22 +01:00
Invokes `changeText` event handler on the element or parent element in the tree.
``` jsx
import { View , TextInput } from 'react-native' ;
2020-07-28 11:50:49 +02:00
import { render , fireEvent } from '@testing-library/react-native' ;
2018-11-23 15:03:22 +01:00
const onChangeTextMock = jest . fn ( ) ;
const CHANGE _TEXT = 'content' ;
2020-07-24 22:53:34 +02:00
const { getByPlaceholderText } = render (
2018-11-23 15:03:22 +01:00
< View >
2020-05-08 14:37:28 +00:00
< TextInput placeholder = "Enter data" onChangeText = { onChangeTextMock } / >
2018-11-23 15:03:22 +01:00
< / View >
) ;
2020-07-24 22:53:34 +02:00
fireEvent . changeText ( getByPlaceholderText ( 'Enter data' ) , CHANGE _TEXT ) ;
2018-11-23 15:03:22 +01:00
```
2019-07-16 16:19:59 +02:00
### `fireEvent.scroll: (element: ReactTestInstance, ...data: Array<any>) => void`
2018-11-23 15:03:22 +01:00
Invokes `scroll` event handler on the element or parent element in the tree.
2019-09-27 10:24:54 +02:00
#### On a `ScrollView`
2018-11-23 15:03:22 +01:00
``` jsx
2019-09-27 10:24:54 +02:00
import { ScrollView , Text } from 'react-native' ;
2020-07-28 11:50:49 +02:00
import { render , fireEvent } from '@testing-library/react-native' ;
2018-11-23 15:03:22 +01:00
const onScrollMock = jest . fn ( ) ;
const eventData = {
nativeEvent : {
contentOffset : {
y : 200 ,
} ,
} ,
} ;
2020-05-08 14:37:28 +00:00
const { getByText } = render (
< ScrollView onScroll = { onScrollMock } >
2018-11-23 15:03:22 +01:00
< Text > XD < / Text >
< / ScrollView >
) ;
2020-05-08 14:37:28 +00:00
fireEvent . scroll ( getByText ( 'scroll-view' ) , eventData ) ;
2018-11-23 15:03:22 +01:00
```
2019-09-27 10:24:54 +02:00
#### On a `FlatList`
``` jsx
import { FlatList , View } from 'react-native' ;
2020-07-28 11:50:49 +02:00
import { render , fireEvent } from '@testing-library/react-native' ;
2019-09-27 10:24:54 +02:00
const onEndReached = jest . fn ( ) ;
2020-08-31 11:07:58 +03:00
const { getByTestId } = render (
2019-09-27 10:24:54 +02:00
< FlatList
data = { Array . from ( { length : 10 } , ( _ , key ) => ( { key : ` ${ key } ` } ) ) }
renderItem = { ( ) => < View style = { { height : 500 , width : 100 } } / > }
onEndReached = { onEndReached }
onEndReachedThreshold = { 0.2 }
2020-08-31 11:07:58 +03:00
testID = "flat-list"
2019-09-27 10:24:54 +02:00
/ >
) ;
const eventData = {
nativeEvent : {
contentOffset : {
y : 500 ,
} ,
contentSize : {
// Dimensions of the scrollable content
height : 500 ,
width : 100 ,
} ,
layoutMeasurement : {
// Dimensions of the device
height : 100 ,
width : 100 ,
} ,
} ,
} ;
2020-08-31 11:07:58 +03:00
fireEvent . scroll ( getByTestId ( 'flat-list' ) , eventData ) ;
2019-09-27 10:24:54 +02:00
expect ( onEndReached ) . toHaveBeenCalled ( ) ;
```
2020-12-11 12:17:55 -05:00
:::note
If you're noticing that components are not being found on a list, even after mocking a scroll event, try changing the [`initialNumToRender` ](https://reactnative.dev/docs/flatlist#initialnumtorender ) that you have set. If you aren't comfortable changing the code to accept this prop from the unit test, try using an e2e test that might better suit what use case you're attempting to replicate.
:::
2020-05-18 17:49:54 +02:00
## `waitFor`
2018-11-23 15:03:22 +01:00
2020-05-18 17:49:54 +02:00
- [`Example code` ](https://github.com/callstack/react-native-testing-library/blob/master/src/__tests__/waitFor.test.js )
2019-01-15 14:25:28 -02:00
2018-11-23 15:03:22 +01:00
Defined as:
``` jsx
2020-05-18 17:49:54 +02:00
function waitFor < T > (
2018-11-23 15:03:22 +01:00
expectation : ( ) => T ,
2020-05-18 17:49:54 +02:00
{ timeout : number = 4500 , interval : number = 50 }
2018-11-23 15:03:22 +01:00
) : Promise < T > { }
```
2020-05-18 17:49:54 +02:00
Waits for non-deterministic periods of time until your element appears or times out. `waitFor` periodically calls `expectation` every `interval` milliseconds to determine whether the element appeared or not.
2018-11-23 15:03:22 +01:00
2020-06-10 08:17:01 +02:00
``` jsx
2020-07-28 11:50:49 +02:00
import { render , waitFor } from '@testing-library/react-native' ;
2020-06-10 08:17:01 +02:00
test ( 'waiting for an Banana to be ready' , async ( ) => {
const { getByText } = render ( < Banana / > ) ;
await waitFor ( ( ) => getByText ( 'Banana ready' ) ) ;
} ) ;
```
2020-05-21 16:07:57 +02:00
:::info
In order to properly use `waitFor` you need at least React >=16.9.0 (featuring async `act` ) or React Native >=0.60 (which comes with React >=16.9.0).
:::
2020-06-10 08:17:01 +02:00
## `waitForElementToBeRemoved`
- [`Example code` ](https://github.com/callstack/react-native-testing-library/blob/master/src/__tests__/waitForElementToBeRemoved.test.js )
Defined as:
2018-11-23 15:03:22 +01:00
``` jsx
2020-06-10 08:17:01 +02:00
function waitForElementToBeRemoved < T > (
expectation : ( ) => T ,
{ timeout : number = 4500 , interval : number = 50 }
) : Promise < T > { }
```
2018-11-23 15:03:22 +01:00
2020-06-10 08:17:01 +02:00
Waits for non-deterministic periods of time until queried element is removed or times out. `waitForElementToBeRemoved` periodically calls `expectation` every `interval` milliseconds to determine whether the element has been removed or not.
``` jsx
2020-07-28 11:12:32 +02:00
import {
render ,
waitForElementToBeRemoved ,
2020-07-28 11:50:49 +02:00
} from '@testing-library/react-native' ;
2020-06-10 08:17:01 +02:00
test ( 'waiting for an Banana to be removed' , async ( ) => {
2018-11-23 15:03:22 +01:00
const { getByText } = render ( < Banana / > ) ;
2020-06-10 08:17:01 +02:00
await waitForElementToBeRemoved ( ( ) => getByText ( 'Banana ready' ) ) ;
2018-11-23 15:03:22 +01:00
} ) ;
```
2020-06-10 08:17:01 +02:00
This method expects that the element is initally present in the render tree and then is removed from it. If the element is not present when you call this method it throws an error.
You can use any of `getBy` , `getAllBy` , `queryBy` and `queryAllBy` queries for `expectation` parameter.
:::info
In order to properly use `waitForElementToBeRemoved` you need at least React >=16.9.0 (featuring async `act` ) or React Native >=0.60 (which comes with React >=16.9.0).
:::
2020-07-28 11:12:32 +02:00
## `within`, `getQueriesForElement`
2020-05-14 12:51:19 +02:00
- [`Example code` ](https://github.com/callstack/react-native-testing-library/blob/master/src/__tests__/within.test.js )
Defined as:
``` jsx
function within ( instance : ReactTestInstance ) : Queries
2020-07-28 11:12:32 +02:00
function getQueriesForElement ( instance : ReactTestInstance ) : Queries
2020-05-14 12:51:19 +02:00
```
2020-07-28 11:12:32 +02:00
`within` (also available as `getQueriesForElement` alias) performs [queries ](./Queries.md ) scoped to given element.
2020-05-14 12:51:19 +02:00
:::note
Please note that additional `render` specific operations like `update` , `unmount` , `debug` , `toJSON` are _ not _ included.
:::
``` jsx
const detailsScreen = within ( getByA11yHint ( 'Details Screen' ) ) ;
expect ( detailsScreen . getByText ( 'Some Text' ) ) . toBeTruthy ( ) ;
expect ( detailsScreen . getByDisplayValue ( 'Some Value' ) ) . toBeTruthy ( ) ;
2020-05-15 09:52:33 +02:00
expect ( detailsScreen . queryByA11yLabel ( 'Some Label' ) ) . toBeTruthy ( ) ;
await expect ( detailsScreen . findByA11yHint ( 'Some Label' ) ) . resolves . toBeTruthy ( ) ;
2020-05-14 12:51:19 +02:00
```
Use cases for scoped queries include:
2020-05-15 09:52:33 +02:00
- queries scoped to a single item inside a FlatList containing many items
- queries scoped to a single screen in tests involving screen transitions (e.g. with react-navigation)
2020-05-14 12:51:19 +02:00
2018-11-23 15:03:22 +01: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
2020-07-28 11:50:49 +02:00
import { render } from '@testing-library/react-native' ;
2018-11-23 15:03:22 +01:00
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
2020-07-28 11:50:49 +02:00
import { render } from '@testing-library/react-native' ;
2018-11-23 15:03:22 +01:00
const { queryAllByText } = render ( < Forms / > ) ;
const submitButtons = queryAllByText ( 'submit' ) ;
expect ( submitButtons ) . toHaveLength ( 3 ) ; // expect 3 elements
```
2019-02-28 21:53:26 +01:00
## `act`
2020-05-21 16:07:57 +02:00
Useful function to help testing components that use hooks API. By default any `render` , `update` , `fireEvent` , and `waitFor` calls are wrapped by this function, so there is no need to wrap it manually. This method is re-exported from [`react-test-renderer` ](https://github.com/facebook/react/blob/master/packages/react-test-renderer/src/ReactTestRenderer.js#L567] ).