React Testing Library: how to use screen in this case instead of container
Asked Answered
K

1

6

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?

Kirby answered 6/2, 2022 at 18:39 Comment(0)
D
2

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

Deidredeific answered 11/3, 2022 at 5:38 Comment(1)
that may make sense for some cases, but it definitely is not possible to use semantic tags with roles for everything, of the role is not actually applicableKirby

© 2022 - 2024 — McMap. All rights reserved.