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

Why do the Testing Library docs recommend screen.getByRole(...) over destructuring queries from render()?

screen has every query bound to document.body, so you can call queries anywhere in the test. You don't need to destructure them from the return value of render.

The benefits:

  • When you add or remove queries, you don't need to keep the destructuring in sync.
  • Every test reads the same way.
  • It matches what the user sees, including portal content.

A portal renders content outside its parent's DOM node, as modals and tooltips do. That content lands outside the render container, but still inside document.body. So screen still finds it.

You still use the render result when you really need rerender, unmount or container. To limit queries to one part of the page, use within(element).

  • screen queries are bound to document.body.
  • With screen there is no destructuring to keep in sync, and tests read the same way.
  • screen finds portal content such as modals and tooltips.
  • Use the render result for rerender and unmount.
  • Use within to limit queries to one region of the page.