ByTestId
getByTestId、queryByTestId、getAllByTestId、queryAllByTestId、findByTestId、findAllByTestId
API
getByTestId(
// If you're using `screen`, then skip the container argument:
container: HTMLElement,
text: TextMatch,
options?: {
exact?: boolean = true,
normalizer?: NormalizerFn,
}): HTMLElement
container.querySelector(`[data-testid="${yourId}"]`)
的快捷方式(也接受 TextMatch
)。
<div data-testid="custom-element" />
- 原生
- React
- Angular
- Cypress
import {screen} from '@testing-library/dom'
const element = screen.getByTestId('custom-element')
import {render, screen} from '@testing-library/react'
render(<MyComponent />)
const element = screen.getByTestId('custom-element')
import {render, screen} from '@testing-library/angular'
await render(MyComponent)
const element = screen.getByTestId('custom-element')
cy.findByTestId('custom-element').should('exist')
本著指導原則的精神,建議只有在其他查詢不適用於您的使用案例時才使用此方法。使用 data-testid 屬性與您的軟體使用方式不符,應盡可能避免。也就是說,它們比基於 DOM 結構或樣式 CSS 類名稱進行查詢要好得多。從部落格文章「使您的 UI 測試具有彈性以適應變更」中了解更多關於
data-testid
的資訊。
選項
TextMatch 選項
覆寫 data-testid
DOM Testing Library
中的 ...ByTestId
函數預設使用屬性 data-testid
,遵循React Native Web設定的先例,該先例使用 testID
屬性在元素上發出 data-testid
屬性,並且我們建議您在可能的情況下採用該屬性。但是,如果您已經有現有的程式碼庫為此目的使用不同的屬性,您可以透過 configure({testIdAttribute: 'data-my-test-attribute'})
覆寫此值。