跳至主要內容

ByText

getByText, queryByText, getAllByText, queryAllByText, findByText, findAllByText

API

getByText(
// If you're using `screen`, then skip the container argument:
container: HTMLElement,
text: TextMatch,
options?: {
selector?: string = '*',
exact?: boolean = true,
ignore?: string|boolean = 'script, style',
normalizer?: NormalizerFn,
}): HTMLElement

這會搜尋所有具有文字節點,且 textContent 符合指定TextMatch 的元素。

<a href="/about">About ℹ️</a>
import {screen} from '@testing-library/dom'

const aboutAnchorNode = screen.getByText(/about/i)

它也適用於 type 屬性為 submitbuttoninput

<input type="submit" value="Send data" />

選項

TextMatch 選項,外加以下選項

selector

注意

請參閱 getByLabelText 以取得有關如何以及何時使用 selector 選項的更多詳細資訊

ignore

ignore 選項接受一個查詢選擇器。如果 node.matches 對該選擇器回傳 true,則會忽略該節點。預設值為 'script, style',因為通常您不希望選取這些標籤,但如果您的內容位於內嵌腳本檔案中,則可能會回傳 script 標籤。

如果您想要停用此行為,請將 ignore 設定為 false