跳至主要內容

ByLabelText

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 結構的輸入節點

// 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" />
import {screen} from '@testing-library/dom'

const inputNode = screen.getByLabelText('Username')

選項

name

上面的範例不會尋找由元素分隔的標籤文字的輸入節點。 您可以使用 getByRole('textbox', { name: 'Username' }) 來代替,這樣可以避免切換到 aria-labelaria-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'})

注意

如果 <label> 元素上的 for 屬性與非表單元素的 id 屬性匹配,則 getByLabelText 將無法運作。

// 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>