I'm writing tests in Jest for a React app. Let's say I have a web page that contains multiples of a certain element. In the below case, I have two buttons. I want to make queries in my test about the button that is inside of the div element with a test ID of 2.
Is there a way for me to query for that button within the context of that parent div? Something like:
const secondDiv = screen.getByTestId(2);
const buttonOfInterest = secondDiv.getByRole('button', {name: 'Button'});
I've tried the above before, but it doesn't work.
I know that I could assign test ID's to the buttons, but I think it'd be very helpful in other scenarios to be able to make queries within contexts of particular elements (instead of using screen
, which refers to the entire document).