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

Viewed 1633

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-tesid 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.

3 Answers

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

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

if(element) {
    /// Do something...
);

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

I would recommend using a querySelector:

const element = getByTestID('').firstchild;
Related