Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 297
someuser2491 Avatar asked Dec 02 '25 03:12

someuser2491


2 Answers

react-testing-library queries return DOM nodes, so you can use DOM API 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:

  • https://developer.mozilla.org/fr/docs/Web/API/Document/querySelector,
  • https://developer.mozilla.org/fr/docs/Web/API/Document/querySelectorall
like image 143
Florian Motteau Avatar answered Dec 06 '25 03:12

Florian Motteau


I think the more organic approach here is 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/

like image 39
Gaurang Patel Avatar answered Dec 06 '25 02:12

Gaurang Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!