getByRole query for paragraph not working during React testing
Asked Answered
E

2

22

I have created a simple counter app for learning react testing library. But I got stuck when I was testing whether a paragraph is rendered or not with {count} text.

Main.jsx

function Main() {
  const [Count, setCount] = useState(0);

  function handleCount() {
    setCount((c) => c + 1);
  }
  return (
    <div>
      <h1>Counter App</h1>
      <Counter count={Count} />
      <Button label="Click me" handleCount={handleCount} />
    </div>
  );
}

Counter.jsx

function Counter({ count }) {
  return <p>{count}</p>;
}

Main.spec.jsx

it("should render count", () => {
    render(<Main />);
    expect(screen.getByRole("paragraph")).toBeInTheDocument();
});

This test was not enough to get passed. I know that we can add data-testid to <p> DOM node and then we can test this by getByTestId query. But I want to know why my above test case which uses getByRole('paragraph')is getting fail every time.

Elude answered 3/12, 2020 at 9:17 Comment(0)
S
20

getByRole uses the HTML role of different elements. Paragraph is not a valid role, that's why your query doesn't work. You can read more here about getByRole https://testing-library.com/docs/dom-testing-library/api-queries/#byrole and about the different roles in html here: https://www.w3.org/TR/html-aria/#docconformance.

You could for example use getByText instead to achieve what you want (read more about preferred queries here: https://testing-library.com/docs/guide-which-query/).

expect(screen.getByText("0")).toBeInTheDocument();
Stogy answered 3/12, 2020 at 9:24 Comment(5)
What would be the valid role for the paragraph?Elude
p tags doesn't have an implicit role (developer.mozilla.org/en-US/docs/Web/HTML/Element/p) so you have to add a role yourself using aria-role if you want it to have a role. I'm not sure actually which roles would fit, I guess that's very dependant on context.Stogy
The linked w3 document indicates that paragraph is a valid role and the implicit role for a <p>. The role was added to ARIA in June 2018Langue
I should probably acknowledge that, as indicated by @Thejool, MDN incorrectly indicates that <p> has no implicit ARIA role but the ARIA documentation shows paragraph.Langue
Checking in to add that as of September 2023 screen.getByRole("paragraph") cannot find p elements despite it being a valid role. Someone opened an issue in June and it will be fixed in React Testing Library as soon as aria-query releases a new version with the fix in that repo.Cove
T
1

getByText: Outside of forms, text content is the main way users find elements. This method can be used to find non-interactive elements (like divs, spans, and paragraphs)

Check TL Documentation https://testing-library.com/docs/queries/about/#byrole

Tremolo answered 23/2, 2023 at 17:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.