Queries are one of the main building blocks for the React Native Testing Library. They enable you to find relevant elements in the element tree, which represents your application's user interface when running under tests.
All queries described below are accessible in two main ways: through the screen object or by capturing the render function call result.
screen objectThe modern and recommended way of accessing queries is to use the screen object exported by the @testing-library/react-native package. This object will contain methods of all available queries bound to the most recently rendered UI.
render resultThe classic way is to capture query functions, as they are returned from the render function call. This provides access to the same functions as in the case of the screen object.
Each query is composed of two parts: variant and predicate, which are separated by the by word in the middle of the name.
Consider the following query:
For this query, getBy* is the query variant, and *ByRole is the predicate.
The query variants describe the expected number (and timing) of matching elements, so they differ in their return type.
| Variant | Assertion | Return type | Is Async? |
|---|---|---|---|
getBy* |
Exactly one matching element | ReactTestInstance |
No |
getAllBy* |
At least one matching element | Array<ReactTestInstance> |
No |
queryBy* |
Zero or one matching element | ReactTestInstance | null |
No |
queryAllBy* |
No assertion | Array<ReactTestInstance> |
No |
findBy* |
Exactly one matching element | Promise<ReactTestInstance> |
Yes |
findAllBy* |
At least one matching element | Promise<Array<ReactTestInstance>> |
Yes |
Queries work as implicit assertions on the number of matching elements and will throw an error when the assertion fails.
getBy* queriesgetBy* queries return the single matching element for a query, and throw an error if no elements match or if more than one match is found. If you need to find more than one element, then use getAllBy.
getAllBy* queriesgetAllBy* queries return an array of all matching elements for a query and throw an error if no elements match.
queryBy* queriesqueryBy* queries return the first matching node for a query, and return null if no elements match. This is useful for asserting an element that is not present. This throws if more than one match is found (use queryAllBy instead).
queryAllBy* queriesqueryAllBy* queries return an array of all matching nodes for a query and return an empty array ([]) when no elements match.
findBy* queriesfindBy* queries return a promise which resolves when a matching element is found. The promise is rejected if no elements match or if more than one match is found after a default timeout of 1000 ms. If you need to find more than one element use findAllBy* queries.
findAllBy* queriesfindAllBy* queries return a promise which resolves to an array of matching elements. The promise is rejected if no elements match after a default timeout of 1000 ms.
findBy* and findAllBy* queries accept optional waitForOptions object arguments, which can contain timeout, interval and onTimeout properties which have the same meaning as respective options for waitFor function.
In cases when your findBy* and findAllBy* queries throw when unable to find matching elements, it is helpful to pass onTimeout: () => { screen.debug(); } callback using the waitForOptions parameter.
Note: most methods like this one return a ReactTestInstance with following properties that you may be interested in:
*ByRolegetByRole, getAllByRole, queryByRole, queryAllByRole, findByRole, findAllByRole
Returns a ReactTestInstance with matching role or accessibilityRole prop.
In order for *ByRole queries to match an element it needs to be considered an accessibility element:
Text, TextInput and Switch host elements are these by default.View host elements need an explicit accessible prop set to truePressable & TouchableOpacity render host View element with accessible prop already set.name: Finds an element with given role/accessibilityRole and an accessible name (= accessability label or text content).
disabled: You can filter elements by their disabled state (coming either from aria-disabled prop or accessbilityState.disabled prop). The possible values are true or false. Querying disabled: false will also match elements with disabled: undefined (see the wiki for more details).
disabled state.toBeEnabled() / toBeDisabled() Jest matchers.selected: You can filter elements by their selected state (coming either from aria-selected prop or accessbilityState.selected prop). The possible values are true or false. Querying selected: false will also match elements with selected: undefined (see the wiki for more details).
selected state.toBeSelected() Jest matcher.checked: You can filter elements by their checked state (coming either from aria-checked prop or accessbilityState.checked prop). The possible values are true, false, or "mixed".
checked state.toBeChecked() / toBePartiallyChecked() Jest matchers.busy: You can filter elements by their busy state (coming either from aria-busy prop or accessbilityState.busy prop). The possible values are true or false. Querying busy: false will also match elements with busy: undefined (see the wiki for more details).
busy state.toBeBusy() Jest matcher.expanded: You can filter elements by their expanded state (coming either from aria-expanded prop or accessbilityState.expanded prop). The possible values are true or false.
expanded state.toBeExpanded() / toBeCollapsed() Jest matchers.value: Filter elements by their accessibility value, based on either aria-valuemin, aria-valuemax, aria-valuenow, aria-valuetext or accessibilityValue props. Accessiblity value conceptually consists of numeric min, max and now entries, as well as string text entry.
toHaveAccessibilityValue() Jest matcher.*ByLabelTextgetByLabelText, getAllByLabelText, queryByLabelText, queryAllByLabelText, findByLabelText, findAllByLabelText
Returns a ReactTestInstance with matching label:
aria-label/accessibilityLabel proparia-labelledby/accessibilityLabelledBy prop*ByPlaceholderTextgetByPlaceholderText, getAllByPlaceholderText, queryByPlaceholderText, queryAllByPlaceholderText, findByPlaceholderText, findAllByPlaceholderText
Returns a ReactTestInstance for a TextInput with a matching placeholder – may be a string or regular expression.
*ByDisplayValuegetByDisplayValue, getAllByDisplayValue, queryByDisplayValue, queryAllByDisplayValue, findByDisplayValue, findAllByDisplayValue
Returns a ReactTestInstance for a TextInput with a matching display value – may be a string or regular expression.
*ByTextgetByText, getAllByText, queryByText, queryAllByText, findByText, findAllByText
Returns a ReactTestInstance with matching text – may be a string or regular expression.
This method will join <Text> siblings to find matches, similarly to how React Native handles these components. This will allow for querying for strings that will be visually rendered together, but may be semantically separate React components.
*ByHintTextgetByA11yHint, getAllByA11yHint, queryByA11yHint, queryAllByA11yHint, findByA11yHint, findAllByA11yHint getByAccessibilityHint, getAllByAccessibilityHint, queryByAccessibilityHint, queryAllByAccessibilityHint, findByAccessibilityHint, findAllByAccessibilityHint getByHintText, getAllByHintText, queryByHintText, queryAllByHintText, findByHintText, findAllByHintText
Returns a ReactTestInstance with matching accessibilityHint prop.
Please consult Apple guidelines on how accessibilityHint should be used.
*ByTestIdgetByTestId, getAllByTestId, queryByTestId, queryAllByTestId, findByTestId, findAllByTestId
Returns a ReactTestInstance with matching testID prop. testID – may be a string or a regular expression.
In the spirit of the guiding principles, it is recommended to use this only after the other queries don't work for your use case. Using testID attributes do not resemble how your software is used and should be avoided if possible. However, they are particularly useful for end-to-end testing on real devices, e.g. using Detox and it's an encouraged technique to use there. Learn more from the blog post "Making your UI tests resilient to change".
Usually query first argument can be a string or a regex. All queries take at least the hidden option as an optionnal second argument and some queries accept more options which change string matching behaviour. See TextMatch for more info.
includeHiddenElements optionAll queries have the includeHiddenElements option which affects whether elements hidden from accessibility are matched by the query. By default queries will not match hidden elements, because the users of the app would not be able to see such elements.
You can configure the default value with the configure function.
This option is also available as hidden alias for compatibility with React Testing Library.
Examples
Most of the query APIs take a TextMatch as an argument, which means the argument can be either a string or regex.
Given the following render:
Will find a match:
Will NOT find a match
Queries that take a TextMatch also accept an object as the second argument that can contain options that affect the precision of string matching:
exact: Defaults to true; matches full strings, case-sensitive. When false, matches substrings and is not case-sensitive.
exact has no effect on regex argument.regex instead of a string gives you more control over fuzzy matching and should be preferred over { exact: false }.normalizer: An optional function which overrides normalization behavior. See Normalization.exact option defaults to true but if you want to search for a text slice or make text matching case-insensitive you can override it. That being said we advise you to use regex in more complex scenarios.
Before running any matching logic against text, it is automatically normalized. By default, normalization consists of trimming whitespace from the start and end of text, and collapsing multiple adjacent whitespace characters into a single space.
If you want to prevent that normalization, or provide alternative normalization (e.g. to remove Unicode control characters), you can provide a normalizer function in the options object. This function will be given a string and is expected to return a normalized version of that string.
Specifying a value for normalizer replaces the built-in normalization, but you can call getDefaultNormalizer to obtain a built-in normalizer, either to adjust that normalization or to call it from your own normalizer.
getDefaultNormalizer take options object which allows the selection of behaviour:
trim: Defaults to true. Trims leading and trailing whitespace.collapseWhitespace: Defaults to true. Collapses inner whitespace (newlines, tabs repeated spaces) into a single space.To perform a match against text without trimming:
To override normalization to remove some Unicode characters whilst keeping some (but not all) of the built-in normalization behavior:
render from @testing-library/react-native exposes additional queries that should not be used in integration or component testing, but some users (like component library creators) interested in unit testing some components may find helpful.
The interface is the same as for other queries, but we won't provide full names so that they're harder to find by search engines.
UNSAFE_ByTypeUNSAFE_getByType, UNSAFE_getAllByType, UNSAFE_queryByType, UNSAFE_queryAllByType
Returns a ReactTestInstance with matching a React component type.
This query has been marked unsafe, since it requires knowledge about implementation details of the component. Use responsibly.
UNSAFE_ByPropsUNSAFE_getByProps, UNSAFE_getAllByProps, UNSAFE_queryByProps, UNSAFE_queryAllByProps
Returns a ReactTestInstance with matching props object.
This query has been marked unsafe, since it requires knowledge about implementation details of the component. Use responsibly.