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.
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:
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With