11

I have a structure like this:

<div data-test-locator="MyId">
    <input value="some" type="checkbox" checked />
</div>

I need to test if the checkbox is checked. But how can I get it in the first place? I can get an element with a test id like this: getByTestId('MyId') But how can I get its child input?

2
  • Why not put the test ID on the thing you want to interact with?
    – jonrsharpe
    Commented Jan 19, 2020 at 8:37
  • 1
    It's generated by a third party. But I need to test that checkbox is checked somehow.
    – Anna
    Commented Jan 19, 2020 at 8:40

4 Answers 4

11

If you know the structure would not change, you can use firstChild

expect((getByTestId('MyId').firstChild).checked).toEqual(true)

9

Using querySelector we don't need to know the structure:

const input = screen
  .getByTestId('MyId')
  .querySelector('input')

expect(input.checked)
  .toBeTruthy()
3

For now, I resolved it by getting my checkbox by value:

expect(getByDisplayValue('some').checked).toBeTruthy();

3

I'm not sure if this is a new introduction to the Testing Library, but there is a documentation page titled "Querying Within Elements" which gives an example like this, using within:

import {render, screen, within} from '@testing-library/react'

render(<MyComponent />)
const wrapperDiv = screen.getByTestId('MyId')
const checkbox = within(wrapperDiv).getByRole('checkbox')

Given a slightly modified data attribute on the MyComponent element:

<div data-testid="MyId">
    <input value="some" type="checkbox" checked />
</div>

Though according to byTestId docs right now it's encouraged to try to use other queries like byRole, byLabelText etc before relying on byTestId, if possible.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.