Queries
Variants#
getByqueries are shown by default in the query documentation below.
getBy#
getBy* queries return the first matching node for a query, and throw an error
if no elements match or if more than one match is found (use getAllBy
instead).
getAllBy#
getAllBy* queries return an array of all matching nodes for a query, and throw
an error if no elements match.
queryBy#
queryBy* 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#
queryAllBy* queries return an array of all matching nodes for a query, and
return an empty array ([]) if no elements match.
findBy#
findBy* queries return a promise which resolves when an element is found which
matches the given query. The promise is rejected if no element is found or if
more than one element is found after a default timeout of 4500ms. If you need
to find more than one element, then use findAllBy.
Note, this is a simple combination of
getBy*queries andwaitForElement. ThefindBy*queries accept thewaitForElementoptions as the last argument. (i.e.findByText(container, 'text', queryOptions, waitForElementOptions))
findAllBy#
findAllBy* queries return a promise which resolves to an array of elements
when any elements are found which match the given query. The promise is rejected
if no elements are found after a default timeout of 4500ms.
Options#
The argument to a query can be a string, regular expression, or function. There are also options to adjust how node text is parsed.
See TextMatch for documentation on what can be passed to a query.
screen#
All of the queries exported by DOM Testing Library accept a container as the
first argument. Because querying the entire document.body is very common, DOM
Testing Library also exports a screen object which has every query that is
pre-bound to document.body (using the
within
functionality).
Here's how you use it:
screen.debug#
For convenience screen also exposes a debug method in addition to the queries.
This method is essentially a shortcut for console.log(prettyDOM()). It
supports debugging the document, a single element, or an array of elements.
Queries#
NOTE: These queries are the base queries and require you pass a
containeras the first argument. Most framework-implementations of Testing Library provide a pre-bound version of these queries when you render your components with them which means you do not have to provide a container. In addition, if you just want to querydocument.bodythen you can use thescreenexport as demonstrated above.
ByLabelText#
getByLabelText, queryByLabelText, getAllByLabelText, queryAllByLabelText findByLabelText, findAllByLabelText
This will search for the label that matches the given TextMatch,
then find the element associated with that label.
The example below will find the input node for the following DOM structures:
It will NOT find the input node for label text broken up by elements. You can
use getByRole('textbox', { name: 'Username' }) instead which is robust against
switching to aria-label or aria-labelledby.
If it is important that you query an actual <label> element you can provide a
selector in the options:
ByPlaceholderText#
getByPlaceholderText, queryByPlaceholderText, getAllByPlaceholderText, queryAllByPlaceholderText, findByPlaceholderText, findAllByPlaceholderText
This will search for all elements with a placeholder attribute and find one that
matches the given TextMatch.
Note
A placeholder is not a good substitute for a label so you should generally use
getByLabelTextinstead.
ByText#
getByText, queryByText, getAllByText, queryAllByText, findByText, findAllByText
This will search for all elements that have a text node with textContent
matching the given TextMatch.
It also works with inputs whose type attribute is either submit or
button:
Note
See
getByLabelTextfor more details on how and when to use theselectoroption
The ignore option accepts a query selector. If the
node.matches
returns true for that selector, the node will be ignored. This defaults to
'script' because generally you don't want to select script tags, but if your
content is in an inline script file, then the script tag could be returned.
If you'd rather disable this behavior, set ignore to false.
ByAltText#
getByAltText, queryByAltText, getAllByAltText, queryAllByAltText, findByAltText, findAllByAltText
This will return the element (normally an <img>) that has the given alt
text. Note that it only supports elements which accept an alt attribute:
<img>,
<input>,
and <area>
(intentionally excluding
<applet>
as it's deprecated).
ByTitle#
getByTitle, queryByTitle, getAllByTitle, queryAllByTitle, findByTitle, findAllByTitle
Returns the element that has the matching title attribute.
Will also find a title element within an SVG.
ByDisplayValue#
getByDisplayValue, queryByDisplayValue, getAllByDisplayValue, queryAllByDisplayValue, findByDisplayValue, findAllByDisplayValue
Returns the input, textarea, or select element that has the matching
display value.
input#
textarea#
select#
In case of select, this will search for a <select> whose selected <option>
matches the given TextMatch.
ByRole#
getByRole, queryByRole, getAllByRole, queryAllByRole, findByRole, findAllByRole
Queries for elements with the given role (and it also accepts a
TextMatch). Default roles are taken into consideration e.g.
<button /> has the button role without explicitly setting the role
attribute. The
W3C HTML recommendation lists
all HTML elements with their default ARIA roles. Additionally, as DOM Testing
Library uses aria-query under the hood to find those elements by their default
ARIA roles, you can find in their docs
which HTML Elements with inherent roles are mapped to each role.
You can query the returned element(s) by their
accessible name. The accessible name is
for simple cases equal to e.g. the label of a form element, or the text content
of a button, or the value of the aria-label attribute. It can be used to query
a specific element if multiple elements with the same role are present on the
rendered content. For an in-depth guide check out
"What is an accessible name?" from ThePacielloGroup.
If you only query for a single element with getByText('The name') it's
oftentimes better to use getByRole(expectedRole, { name: 'The name' }). The
accessible name query does not replace other queries such as *ByAlt or
*ByTitle. While the accessible name can be equal to these attributes, it does
not replace the functionality of these attributes. For example
<img aria-label="fancy image" src="fancy.jpg" /> will be returned for both
getByAlt('fancy image') and getByRole('image', { name: 'fancy image' }).
However, the image will not display its description if fancy.jpg could not be
loaded. Whether you want assert this functionality in your test or not is up to
you.
If you set hidden to true elements that are normally excluded from the
accessibility tree are considered for the query as well. The default behavior
follows https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion with the exception of
role="none" and role="presentation" which are considered in the query in any
case. For example in
getByRole('button') would only return the Close dialog-button. To make
assertions about the Open dialog-button you would need to use
getAllByRole('button', { hidden: true }).
The default value can be configured.
ByTestId#
getByTestId, queryByTestId, getAllByTestId, queryAllByTestId, findByTestId, findAllByTestId
A shortcut to container.querySelector(`[data-testid="${yourId}"]`) (and it
also accepts a TextMatch).
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 data-testid attributes do not resemble how your software is used and should be avoided if possible. That said, they are way better than querying based on DOM structure or styling css class names. Learn more about
data-testids from the blog post "Making your UI tests resilient to change"
Overriding data-testid#
The ...ByTestId functions in DOM Testing Library use the attribute
data-testid by default, following the precedent set by
React Native Web
which uses a testID prop to emit a data-testid attribute on the element, and
we recommend you adopt that attribute where possible. But if you already have an
existing codebase that uses a different attribute for this purpose, you can
override this value via
configure({testIdAttribute: 'data-my-test-attribute'}).
TextMatch#
Several APIs accept a TextMatch which can be a string, regex or a
function which returns true for a match and false for a mismatch.
Precision#
Some APIs accept an object as the final argument that can contain options that affect 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 onregexorfunctionarguments.- In most cases using a 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. SeeNormalization.
Normalization#
Before running any matching logic against text in the DOM, DOM Testing Library
automatically normalizes that text. 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.
Note: 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 which allows the selection of
behaviour:
trim: Defaults totrue. Trims leading and trailing whitespacecollapseWhitespace: 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:
TextMatch Examples#
Given the following HTML:
Will find the div:
Will not find the div: