CodePark/ questions / Testing Library queries
START PRACTICINGPRACTICE
Frontend question · Testing › Testing Library queries

Explain the difference between getBy*, queryBy* and findBy* queries, and when you'd use each.

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 null when 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 in waitFor. 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* returns null, so use it only to assert that something is absent.
  • findBy* is async: it is getBy* plus waitFor, with a 1000ms default timeout.
  • The All variants (getAllBy*, queryAllBy*, findAllBy*) return arrays of matches.
  • Prefer getBy* errors for debugging, because they print the DOM.