Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access child element from parent using react testing library?

I have DOM like so:

<label value="false" data-testid="source" class="StyledSwitch">
    <input type="checkbox" name="source" >
    <i class="ball-container"></i>
    <span class="label" data-enabled="On" data-disabled="Off"></span>
</label>

How can I access input element using label with data-testid source

I have tried something like below,

const element = screen.getByTestId('source').firstChild();

but this gives error "object is possibly null" cannot invoke an object which is possibly null. How to fix this?

Could someone help me with this? Thanks.

like image 344
stackuser Avatar asked Oct 15 '25 08:10

stackuser


2 Answers

You could use a querySelector to select the input, like this:

const element = screen.getByTestId('source').querySelector('input');

if (element) {
    /// Do something...
);
like image 172
vonny Avatar answered Oct 18 '25 11:10

vonny


const element = getByTestId('source').firstChild;

like image 25
sreejith Avatar answered Oct 18 '25 13:10

sreejith



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!