Queries
Queries are one of the main building blocks of React Native Testing Library. They let you find elements in the element tree, which represents your application's user interface when running under tests.
Accessing queries
All queries described below are accessible in two main ways: through the screen object or by capturing the result of the render function call.
Using screen object
The recommended way to access queries is to use the screen object exported by @testing-library/react-native. It contains methods for all available queries bound to the most recently rendered UI.
Using render result
The classic way is to capture query functions returned from the render function call. This provides access to the same functions as the screen object.
Query parts
Each query is composed of two parts: variant and predicate, separated by the word by in the middle.
Consider the query getByRole():
getBy*is the query variant*ByRoleis the predicate
Query variant
The query variants describe the expected number (and timing) of matching elements, so they differ in return type.
Queries work as implicit assertions on the number of matching elements and throw an error when the assertion fails.
getBy* queries
getBy* 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, use getAllBy.
getAllBy* queries
getAllBy* queries return an array of all matching elements for a query and throw an error if no elements match.
queryBy* queries
queryBy* queries return the first matching node for a query and return null if no elements match. This is useful for asserting that an element is not present. This throws if more than one match is found (use queryAllBy instead).
queryAllBy* queries
queryAllBy* queries return an array of all matching nodes for a query and return an empty array ([]) when no elements match.
findBy* queries
findBy* queries return a promise that 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* queries
findAllBy* queries return a promise that 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.
When your findBy* and findAllBy* queries throw because they can't find matching elements, it's helpful to pass onTimeout: () => { screen.debug(); } callback using the waitForOptions parameter.
Query predicates
Note: most methods like this one return a ReactTestInstance with the following properties that you may be interested in:
*ByRole
getByRole, getAllByRole, queryByRole, queryAllByRole, findByRole, findAllByRole
Returns a ReactTestInstance with matching role or accessibilityRole prop.
For *ByRole queries to match an element, it needs to be considered an accessibility element:
Text,TextInputandSwitchhost elements are these by default.Viewhost elements need an explicitaccessibleprop set totrue- Some React Native composite components like
Pressable&TouchableOpacityrender hostViewelement withaccessibleprop already set.
Options
-
name: Finds an element with the givenrole/accessibilityRoleand an accessible name (= accessibility label or text content). -
disabled: You can filter elements by their disabled state (coming either fromaria-disabledprop oraccessibilityState.disabledprop). The possible values aretrueorfalse. Queryingdisabled: falsewill also match elements withdisabled: undefined(see the wiki for more details).- See React Native's accessibilityState docs to learn more about the
disabledstate. - This option can alternatively be expressed using the
toBeEnabled()/toBeDisabled()Jest matchers.
- See React Native's accessibilityState docs to learn more about the
-
selected: You can filter elements by their selected state (coming either fromaria-selectedprop oraccessibilityState.selectedprop). The possible values aretrueorfalse. Queryingselected: falsewill also match elements withselected: undefined(see the wiki for more details).- See React Native's accessibilityState docs to learn more about the
selectedstate. - This option can alternatively be expressed using the
toBeSelected()Jest matcher.
- See React Native's accessibilityState docs to learn more about the
-
checked: You can filter elements by their checked state (coming either fromaria-checkedprop oraccessibilityState.checkedprop). The possible values aretrue,false, or"mixed".- See React Native's accessibilityState docs to learn more about the
checkedstate. - This option can alternatively be expressed using the
toBeChecked()/toBePartiallyChecked()Jest matchers.
- See React Native's accessibilityState docs to learn more about the
-
busy: You can filter elements by their busy state (coming either fromaria-busyprop oraccessibilityState.busyprop). The possible values aretrueorfalse. Queryingbusy: falsewill also match elements withbusy: undefined(see the wiki for more details).- See React Native's accessibilityState docs to learn more about the
busystate. - This option can alternatively be expressed using the
toBeBusy()Jest matcher.
- See React Native's accessibilityState docs to learn more about the
-
expanded: You can filter elements by their expanded state (coming either fromaria-expandedprop oraccessibilityState.expandedprop). The possible values aretrueorfalse.- See React Native's accessibilityState docs to learn more about the
expandedstate. - This option can alternatively be expressed using the
toBeExpanded()/toBeCollapsed()Jest matchers.
- See React Native's accessibilityState docs to learn more about the
-
value: Filter elements by their accessibility value, based on eitheraria-valuemin,aria-valuemax,aria-valuenow,aria-valuetext, oraccessibilityValueprops. Accessibility value conceptually consists of numericmin,max, andnowentries, as well as stringtextentry.- See React Native accessibilityValue docs to learn more about the accessibility value concept.
- This option can alternatively be expressed using the
toHaveAccessibilityValue()Jest matcher.
*ByLabelText
getByLabelText, getAllByLabelText, queryByLabelText, queryAllByLabelText, findByLabelText, findAllByLabelText
Returns a ReactTestInstance with matching label:
- either by matching
aria-label/accessibilityLabelprop - or by matching the text content of the view referenced by
aria-labelledby/accessibilityLabelledByprop
*ByPlaceholderText
getByPlaceholderText, getAllByPlaceholderText, queryByPlaceholderText, queryAllByPlaceholderText, findByPlaceholderText, findAllByPlaceholderText
Returns a ReactTestInstance for a TextInput with a matching placeholder—may be a string or regular expression.
*ByDisplayValue
getByDisplayValue, getAllByDisplayValue, queryByDisplayValue, queryAllByDisplayValue, findByDisplayValue, findAllByDisplayValue
Returns a ReactTestInstance for a TextInput with a matching display value. The value can be a string or regular expression.
*ByText
getByText, getAllByText, queryByText, queryAllByText, findByText, findAllByText
Returns a ReactTestInstance with matching text. The text can be a string or regular expression.
This method joins <Text> siblings to find matches, similarly to how React Native handles these components. This allows querying for strings that will be visually rendered together but may be semantically separate React components.
*ByHintText
getByA11yHint, 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.
*ByTestId
getByTestId, getAllByTestId, queryByTestId, queryAllByTestId, findByTestId, findAllByTestId
Returns a ReactTestInstance with a matching testID prop. testID may be a string or a regular expression.
In the spirit of the guiding principles, use this only after the other queries don't work for your use case. Using testID attributes doesn't resemble how your software is used and should be avoided if possible. However, they're 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".
Common options
Usually the query's first argument can be a string or a regex. All queries take at least the hidden option as an optional second argument, and some queries accept more options that change string matching behavior. See TextMatch for more info.
includeHiddenElements option
All queries have the includeHiddenElements option which affects whether elements hidden from accessibility are matched by the query. By default, queries won't match hidden elements because users of the app wouldn't 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
TextMatch type
Most query APIs take a TextMatch as an argument, which means the argument can be either a string or regex.
Examples
Given the following render:
Will find a match:
Will NOT find a match
Options
Precision
Queries that take a TextMatch also accept an object as the second argument that contains options affecting the precision of string matching:
exact: Defaults totrue; matches full strings, case-sensitive. When false, matches substrings and is not case-sensitive.exacthas no effect on regex argument.- In most cases using a
regexinstead 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.
The 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 said, we advise you to use regex in more complex scenarios.
Normalization
Before running any matching logic against text, it's 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 is 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 takes an options object that allows selection of behavior:
trim: Defaults totrue. Trims leading and trailing whitespace.collapseWhitespace: Defaults totrue. Collapses inner whitespace (newlines, tabs repeated spaces) into a single space.
Normalization Examples
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:
Legacy unit testing helpers
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 they're harder to find via search engines.
UNSAFE_ByType
UNSAFE_getByType, UNSAFE_getAllByType, UNSAFE_queryByType, UNSAFE_queryAllByType
Returns a ReactTestInstance with a matching React component type.
This query has been marked unsafe because it requires knowledge about implementation details of the component. Use responsibly.
UNSAFE_ByProps
UNSAFE_getByProps, UNSAFE_getAllByProps, UNSAFE_queryByProps, UNSAFE_queryAllByProps
Returns a ReactTestInstance with matching props.
This query has been marked unsafe because it requires knowledge about implementation details of the component. Use responsibly.
