getBy* finds an element now or throws, queryBy* returns null when nothing matches, and findBy* waits for the element and returns a promise.
getBy*:
- It returns the matching element synchronously, right away.
- It throws if there is no match, or if there is more than one.
- Use it for elements that should be there right now.
- The thrown error prints the DOM, which helps debugging.
queryBy*:
- It returns
nullwhen nothing matches. It still throws on multiple matches. - Use it only to assert that something is not present. Example:
expect(screen.queryByRole('alert')).not.toBeInTheDocument().
findBy*:
- It returns a promise.
- It is
getBy*wrapped inwaitFor. It retries until the element appears or the timeout passes. The default timeout is 1000ms. - Use it for elements that appear after async work, such as data loading.
Each one has an All variant: getAllBy*, queryAllBy* and findAllBy*. These return an array when several elements match.
getBy*is synchronous and throws on 0 matches or on more than 1 match.queryBy*returnsnull, so use it only to assert that something is absent.findBy*is async: it isgetBy*pluswaitFor, with a 1000ms default timeout.- The
Allvariants (getAllBy*,queryAllBy*,findAllBy*) return arrays of matches. - Prefer
getBy*errors for debugging, because they print the DOM.
Read more
- About queries (https://testing-library.com/docs/queries/about)testing-library.com