How to make queries in Jest test within context of particular element?

Viewed 2491

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).

enter image description here

2 Answers

You can use ā€œwithinā€ helper function:

import { screen, within } from '@testing-library/dom';

const someDiv = screen.getByTestId('some-id');
const childButton = within(someDiv).getByRole('button');

In addition to genechk's answer:

If you are writing tests for react app you better use

import { screen, within } from '@testing-library/react'

instead of

import { screen, within } from '@testing-library/dom';
Related