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によって設定され、要素に対してdata-testid
属性を発行するためのtestID
プロパティが使用されています。可能な場合は、この規約を採用することをお勧めします。ただし、この目的に異なる属性を使用する既存のコードベースがある場合は、configure({testIdAttribute: 'data-my-test-attribute'})
を使用してこの値を上書きできます。