Understanding getBy, queryBy, and findBy in React Testing Library
November 20, 2024

Last week, I was tasked with upgrading Jest from version 26 to 29. During this process, I took a closer look at the tests and realized that the most frequently used features are the query methods: getBy, queryBy, findBy, and their All variations.
At first glance, these queries might seem confusing due to their names or translations into other languages. This post will help you understand when and how to use them with clear examples.
getBy
Use when the element must exist in the DOM immediately.
queryBy
Use when the element might not exist, and you want to check safely.
findBy
Use when the element is rendered asynchronously after some event.
Common Mistakes to Avoid:
"Mistakes in selecting query methods can lead to flaky or failing tests. Understanding their nuances ensures that your tests remain robust and user-focused."
- Using
getByfor elements that might not exist: If the element might not be present in the DOM, prefer usingqueryBy.queryByreturnsnullif the element isn't found, whereasgetBywill throw an error if the element is absent, causing unnecessary test failures. - Ignoring asynchronous rendering: If the element is rendered after an event or a delay (e.g., data fetching), make sure to use
findBy. It will automatically wait for the element to appear, preventing issues with asserting before the DOM is updated.
Conclusion
Understanding getBy, queryBy, findBy, and their All variants can make your tests more precise and effective. Use them thoughtfully to align with how users interact with your UI.
Check out the React Testing Library documentation for more tips and advanced usage.