要素内のクエリ
within
(getQueriesForElement
のエイリアス)は DOM 要素を取り、それを生のクエリ関数にバインドして、コンテナーを指定せずに使用できるようにします。この API に基づいて構築されたライブラリに推奨される方法であり、React Testing Library と Vue Testing Library で内部的に使用されています。
例: 「messages」と呼ばれるセクション内だけで「hello」というテキストを取得するには、次のようにできます。
- ネイティブ
- React
- Angular
- Cypress
import {within} from '@testing-library/dom'
const messages = document.getElementById('messages')
const helloMessage = within(messages).getByText('hello')
import {render, within} from '@testing-library/react'
const {getByText} = render(<MyComponent />)
const messages = getByText('messages')
const helloMessage = within(messages).getByText('hello')
import {render, within} from '@testing-library/angular'
const {getByText} = await render(MyComponent)
const messages = getByText('messages')
const helloMessage = within(messages).getByText('hello')
cy.findByText('messages').within(() => {
cy.findByText('hello')
})