在元素內查詢
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')
})