React Testing Library: Get child input inside of TestId element
Asked Answered
T

4

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?

Talc answered 19/1, 2020 at 8:29 Comment(2)
Why not put the test ID on the thing you want to interact with?Attorn
It's generated by a third party. But I need to test that checkbox is checked somehow.Talc
G
11

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

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

Grammarian answered 21/1, 2020 at 11:15 Comment(0)
I
9

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

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

expect(input.checked)
  .toBeTruthy()
Intendment answered 18/1, 2022 at 1:17 Comment(0)
T
3

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

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

Talc answered 19/1, 2020 at 9:5 Comment(0)
U
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.

Uniseptate answered 24/10, 2022 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.