API
Table of contents:
render
screen
cleanup
fireEvent
fireEvent[eventName]
waitFor
waitForElementToBeRemoved
within
,getQueriesForElement
query
APIsqueryAll
APIsact
renderHook
This page gathers public API of React Native Testing Library along with usage examples.
render
Defined as:
Deeply renders given React element and returns helpers to query the output components structure.
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.
The render
method returns a RenderResult
object having properties described below.
info
Latest render
result is kept in screen
variable that can be imported from @testing-library/react-native
package.
Using screen
instead of destructuring render
result is recommended approach. See this article from Kent C. Dodds for more details.
...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 for a complete list.
Example
update
Also available under rerender
alias
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.
unmount
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).
debug
Pretty prints deeply rendered component passed to render
with optional message on top.
logs optional message and colored JSX:
debug.shallow
Pretty prints shallowly rendered component passed to render
with optional message on top.
toJSON
Get the rendered component JSON representation, e.g. for snapshot testing.
container
A reference to the rendered root element.
screen
Hold the value of latest render call for easier access to query and other functions returned by render
.
Its value is automatically cleared after each test by calling cleanup
. If no render
call has been made in a given test then it holds a special object that implements RenderResult
but throws a helpful error on each property and method access.
cleanup
Unmounts React trees that were mounted with render
and clears screen
variable that holds latest render
output.
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.
For example, if you're using the jest
testing framework, then you would need to use the afterEach
hook like so:
The afterEach(cleanup)
call also works in describe
blocks:
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).
fireEvent
Fires native-like event with data.
Invokes a given event handler (whether native or custom) on the element, bubbling to the root of the rendered tree.
note
Please note that from version 7.0
fireEvent
performs checks that should prevent events firing on disabled elements.
An example using fireEvent
with native events that aren't already aliased by the fireEvent
api.
fireEvent[eventName]
Convenience methods for common events like: press
, changeText
, scroll
.
fireEvent.press
Invokes press
event handler on the element or parent element in the tree.
fireEvent.changeText
Invokes changeText
event handler on the element or parent element in the tree.
fireEvent.scroll
Invokes scroll
event handler on the element or parent element in the tree.
ScrollView
On a FlatList
On a note
If you're noticing that components are not being found on a list, even after mocking a scroll event, try changing the 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.
waitFor
Defined as:
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.
info
In order to properly use waitFor
you need at least React >=16.9.0 (featuring async act
) or React Native >=0.61 (which comes with React >=16.9.0).
waitForElementToBeRemoved
Defined as:
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.
This method expects that the element is initially 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.61 (which comes with React >=16.9.0).
within
, getQueriesForElement
Defined as:
within
(also available as getQueriesForElement
alias) performs queries scoped to given element.
note
Please note that additional render
specific operations like update
, unmount
, debug
, toJSON
are not included.
Use cases for scoped queries include:
- 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)
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:
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.
act
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
.
renderHook
Defined as:
Renders a test component that will call the provided callback
, including any hooks it calls, every time it renders. Returns RenderHookResult
object, which you can interact with.
The renderHook
function accepts the following arguments:
callback
The function that is called each render
of the test component. This function should call one or more hooks for testing.
The props
passed into the callback will be the initialProps
provided in the options
to renderHook
, unless new props are provided by a subsequent rerender
call.
options
(Optional)
A RenderHookOptions<Props>
object to modify the execution of the callback
function, containing the following properties:
initialProps
The initial values to pass as props
to the callback
function of renderHook
. The Props
type is determined by the type passed to or inferred by the renderHook
call.
wrapper
A React component to wrap the test component in when rendering. This is usually used to add context providers from React.createContext
for the hook to access with useContext
.
RenderHookResult
object
The renderHook
function returns an object that has the following properties:
result
The current
value of the result
will reflect the latest of whatever is returned from the callback
passed to renderHook
. The Result
type is determined by the type passed to or inferred by the renderHook
call.
rerender
A function to rerender the test component, causing any hooks to be recalculated. If newProps
are passed, they will replace the callback
function's initialProps
for subsequent rerenders. The Props
type is determined by the type passed to or inferred by the renderHook
call.
unmount
A function to unmount the test component. This is commonly used to trigger cleanup effects for useEffect
hooks.
Examples
Here we present some extra examples of using renderHook
API.