Search code examples
react-testing-library

getAllByRole and then getByText combined


How can I combine two RTL screen methods?

I have several H4s on my page, with different text inside. I wish to a) return back all h4s and then b) return a specific one by text

  • I want to retain the check that it was a heading
  • I want to retain the check that the heading was of level h4
  • I want to pull back a specific h4 based on its text

I do not want to just dive right into the text using getByText but test both parts:

const myHeading = screen.getAllByRole('heading', { level: 4 }).getByText("my heading text")

I know I can write a find function to return the element inside the array returned by getAllByRole to find the one with children equalling my text. But it seems quite messy. Is there an easier way to combine two RTL queries?

I tried using within however it seems within is designed for a page section not an array, so it didn't seem to work.


Solution

  • I have usually accessed heading text through the name option. Perhaps this could work in your case?

    i.e.

    screen.getByRole("heading", {level: 4, name: "text in the heading"})