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).
screenqueries are bound todocument.body.- With
screenthere is no destructuring to keep in sync, and tests read the same way. screenfinds portal content such as modals and tooltips.- Use the render result for
rerenderandunmount. - Use
withinto limit queries to one region of the page.
Read more
- RTL API (https://testing-library.com/docs/react-testing-library/api)testing-library.com
- About queries (https://testing-library.com/docs/queries/about)testing-library.com