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.