getByRole query for paragraph not working during React testing

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.

2 Answers

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 and about the different roles in html here: .

You could for example use getByText instead to achieve what you want (read more about preferred queries here: ).

expect(screen.getByText("0")).toBeInTheDocument(); 
5

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like