4

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.

3 Answers 3

3

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

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

if (element) {
    /// Do something...
);
Sign up to request clarification or add additional context in comments.

1 Comment

"Avoid direct Node access. Prefer using the methods from Testing Library."
1

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

3 Comments

Do you mind going further in depth to explain the reasoning behind this answer?
I don't know why it's downvoted. It worked for me as the best answer here.
"Avoid direct Node access. Prefer using the methods from Testing Library."
0

I would recommend using a querySelector:

const element = getByTestID('').firstchild;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.