jest-native
Custom jest matchers to test the state of React Native.
The problem
You want to use jest to write tests that assert various things
about the state of a React Native app. As part of that goal, you want to avoid all the repetitive
patterns that arise in doing so like checking for a native element's props, its text content, its
styles, and more.
This solution
The jest-native
library provides a set of custom jest matchers that you can use to extend jest.
These will make your tests more declarative, clear to read and to maintain.
Compatibility
These matchers should, for the most part, be agnostic enough to work with any React Native testing
utilities, but they are primarily intended to be used with
RNTL. Any issues raised with existing
matchers or any newly proposed matchers must be viewed through compatibility with that library and
its guiding principles first.
Installation
This module should be installed as one of your project's devDependencies
:
npm install --save-dev @testing-library/jest-native
You will need react-test-renderer
, react
, and react-native
installed in order to use this
package.
Usage
Import @testing-library/jest-native/extend-expect
once (for instance in your
tests setup file) and you're good
to go:
Alternatively, you can selectively import only the matchers you intend to use, and extend jest's
expect
yourself:
Matchers
jest-native
has only been tested to work with RNTL
. Keep in mind that these queries will only
work on UI elements that bridge to native.
toBeDisabled
Check whether or not an element is disabled from a user perspective.
This matcher will check if the element or its parent has a disabled
prop, or if it has
`accessibilityState={{disabled: true]}.
It also works with accessibilityStates={['disabled']}
for now. However, this prop is deprecated in
React Native 0.62
Examples
toBeEnabled
Check whether or not an element is enabled from a user perspective.
Works similarly to expect().not.toBeDisabled()
.
Examples
toBeEmpty
Check that the given element has no content.
Examples
toContainElement
Check if an element contains another element as a descendant. Again, will only work for native
elements.
Examples
toHaveProp
Check that an element has a given prop.
You can optionally check that the attribute has a specific expected value.
Examples
toHaveTextContent
Check if an element or its children have the supplied text.
This will perform a partial, case-sensitive match when a string match is provided. To perform a
case-insensitive match, you can use a RegExp
with the /i
modifier.
To enforce matching the complete text content, pass a RegExp
.
Examples
toHaveStyle
Check if an element has the supplied styles.
You can pass either an object of React Native style properties, or an array of objects with style
properties. You cannot pass properties from a React Native stylesheet.