'React Testing Library: how to use screen in this case instead of container
in react testing library, as per the conventions, it is better to use screen than to destructure the methods from render.
I have a component, where I need to test the text that is rendered. The top level container in this component is a div, so there is no accessible query to get the text match. How do I use screen to do a text match?
I have currently resorted to using container from the destructured props, and then doing a text match on container.
// MyComponent - simplified
const MyComponent = () => <div> some text </div>
// test
const { container } = render(<MyComponent />);
expect(container).toHaveTextContent(...)
Reference: https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-screen
In the blog post it is mentioned that destructuring is mostly supported for legacy purposes, but there are no use cases which can't be solved using screen. Is this use case solvable using screen?
Solution 1:[1]
You should wrap the item in its specified role (which can be found here).
div
is not defined as a role so you can change it to
h1
which will make it semantic and will also be easier to test. Here is how that will look like
function App(){
return <h1>Some random text</h1>
}
// Test
describe("App component", () => {
it("renders heading", () => {
render(<App />);
expect(screen.getByRole('heading',{level:1})).toBeInTheDocument()
});
});
A similar answer can be found here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mubashir Waheed |