What's the difference between getBy, findBy and queryBy in React Testing Library

testing
Back

Queries are the methods that React Testing Library gives us to find elements on the page. There are three of them: get, find and query.

I find myself sometimes forgetting what are the differences between these three query methods. So I came up with a mnemonic rule to never forget again.

get

I like to think of get queries as "this element should be present".

Hence, if no element is found, the query will throw an error

find

With find queries, my thinking is "this element should eventually be present".

That is, the query will return a promise.

React Testing Library will wait for a certain amount of time for the element to be found. If the element is not found within that time, it'll throw an error.

query

Finally, for query methods, I think in terms of "this element might be present".

Compared to get queries, the query methods will return null instead of throwing an error if the element is not found.

Conclusion