ラベルテキストによる絞り込み
getByLabelText、queryByLabelText、getAllByLabelText、queryAllByLabelText、findByLabelText、findAllByLabelText
API
getByLabelText(
// If you're using `screen`, then skip the container argument:
container: HTMLElement,
text: TextMatch,
options?: {
selector?: string = '*',
exact?: boolean = true,
normalizer?: NormalizerFn,
}): HTMLElement
これは、指定された TextMatch
に一致するラベルを検索し、そのラベルに関連付けられている要素を検索します。
次の例は、次の DOM 構造の input ノードを検索します。
// for/htmlFor relationship between label and form element id
<label for="username-input">Username</label>
<input id="username-input" />
// The aria-labelledby attribute with form elements
<label id="username-label">Username</label>
<input aria-labelledby="username-label" />
// Wrapper labels
<label>Username <input /></label>
// Wrapper labels where the label text is in another child element
<label>
<span>Username</span>
<input />
</label>
// aria-label attributes
// Take care because this is not a label that users can see on the page,
// so the purpose of your input must be obvious to visual users.
<input aria-label="Username" />
- ネイティブ
- React
- Angular
- Cypress
import {screen} from '@testing-library/dom'
const inputNode = screen.getByLabelText('Username')
import {render, screen} from '@testing-library/react'
render(<Login />)
const inputNode = screen.getByLabelText('Username')
import {render, screen} from '@testing-library/angular'
await render(Login)
const inputNode = screen.getByLabelText('Username')
cy.findByLabelText('Username').should('exist')
オプション
name
上の例では、ラベルテキストが要素で分割されている場合は、input ノードが見つかりません。その代わりに、getByRole('textbox', { name: 'Username' })
を使用できます。これは aria-label
または aria-labelledby
に切り替わった場合に堅固になります。
selector
特定の要素 (例: <input>
) を照会することが重要な場合は、オプションで selector
を指定できます。
// Multiple elements labelled via aria-labelledby
<label id="username">Username</label>
<input aria-labelledby="username" />
<span aria-labelledby="username">Please enter your username</span>
// Multiple labels with the same text
<label>
Username
<input />
</label>
<label>
Username
<textarea></textarea>
</label>
const inputNode = screen.getByLabelText('Username', {selector: 'input'})
注意
getByLabelText
は、<label>
要素のfor
属性と、フォーム要素以外のid
属性が一致する場合には機能しません。
// This case is not valid
// for/htmlFor between label and an element that is not a form element
<section id="photos-section">
<label for="photos-section">Photos</label>
</section>