6

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 2

8

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');

1
  • 1
    import { screen, within } from '@testing-library/react' If you're writing a react app. Same functionality.
    – Lucas D
    Commented Aug 13, 2021 at 18:10
1

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';

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.