How to get the child div of parent div with some test id using react testing library?

Viewed 15679

i want to get the div element within parent element with some test-id

what i am trying to do?

I have a parent div with test-id "parent-2" and it has a div element within it that has text Remove.

i want to retreive this Remove div element. also there is multiple Remove div elements. something like below

<div data-test-id="parent-1">
    <div>Remove</div>
</div>
<div data-test-id="parent-2">
    <div>Remove</div>
</div>
<div data-test-id="parent-3">
    <div>Remove</div>
</div>

So in the above html code i want to click Remove div from div with parent test-id = "parent-2"

I have tried to do like below

utils.fireEvent.click(getByText('Remove'));

this throws error found multiple instances of Remove.

I tried also this utils.fireEvent.click(getByTestId('parent-2').children[0];

this works. but this accesses the first child of the parent. however wanted to be more specific with the query.

So how can i fix this such that i can click Remove div belong to div of test-id "parent-2"

thanks.

2 Answers

react-testing-library queries return DOM nodes, so you can use DOM APIs on top. You need something like this :

utils.fireEvent.click(getByTestId('parent-1').querySelector('div'));

querySelector takes a CSS selector, so you could give your inner div a class and be more specific :

utils.fireEvent.click(getByTestId('parent-1').querySelector('.myClass'));

see:

I think the more organic approach here it to use within,

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

const secondParent = getByTestId('parent-2');
utils.fireEvent.click(within(secondParent).getByText('Remove'));

Here is the docs description of within,

within (an alias to getQueriesForElement) takes a DOM element and binds it to the raw query functions, allowing them to be used without specifying a container. It is the recommended approach for libraries built on this API and is used under the hood in React Testing Library and Vue Testing Library.

Reference:

https://testing-library.com/docs/dom-testing-library/api-within/

Related