DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Chidera Ani
Chidera Ani

Posted on • Originally published at Medium on

The difference between get, find, query (React Testing Library).

Choosing a suitable query type while working with React Testing Library.

Intro

React Testing Library (RTL) gives developers methods to find elements on the component it rendered for testing, these methods are called queries. There are 3 main types of RTL query types namely get, find and query.

In this guide we’ll be looking at the differences and tips to note while working with any of these query types.

get

  • getBy : returns the matching node, however will throw an error if multiple matches or no matches are found.
  • getAllBy : returns an array of matching nodes if at least one match is found and throws an error if no match is found.

Tip : Use these methods if you expect the element / elements to be present upon query.

query

  • queryBy : returns the matching node if one match is found and null if no match is found, however will throw an error if multiple matches are found.
  • queryAllBy : returns an array of matching nodes if at least one match is found and an empty array if no match is found.

Tip : Use these methods if you are looking to confirm presence of an element / elements.

find

  • findBy : returns a promise that returns the matching node, however will throw an error if multiple matches or no matches are found.
  • findAllBy : returns a promise that returns an array of matching nodes if at least one match is found and throws an error if no match is found.

Tip : Use these methods if the element / elements being queried might display asynchronously (for example, if your element is expected to only display after an event is fired consider using find as it retries the query after some time).

For more information on the queries check out the React Testing Library docs. I’ll appreciate feedback :).

Good luck coding!

Oldest comments (0)

Classic DEV Post:

caching

Web Caching Explained by Buying Milk at the Supermarket