React Testing Library getByRole vs. getByText
September 3, 2025โข110 words
getByRole()
- roles are automatically inferred based on ARIA specs, or they can be manually set
- it's generally preferred because it's more robust, it mirrors more accurately the UX and it tests accessible elements (accessibility tree)
- the returned objects can be queried by accessible names
- it's less performant especially in large DOMs
--
Resources
- ByRole | Testing Library (2024). https://testing-library.com/docs/queries/byrole.
- ARIA in HTML (2025). https://www.w3.org/TR/html-aria/#docconformance.
- Accessible Name and Description Computation 1.1 (2018). https://www.w3.org/TR/accname-1.1/.
- Watson, L. (2024) What is an accessible name? https://www.tpgi.com/what-is-an-accessible-name/.
- ByText | Testing Library (2023). https://testing-library.com/docs/queries/bytext.
- Accessibility tree (no date). https://developer.mozilla.org/en-US/docs/Glossary/Accessibility_tree.
- About queries | Testing Library (2024). https://testing-library.com/docs/queries/about/.