跳至主要內容

自訂查詢

DOM Testing Library 公開了許多用於實作預設查詢的輔助函式。您可以使用這些輔助函式來建立自訂查詢。例如,下面的程式碼展示了一種覆寫預設 testId 查詢以使用不同 data-attribute 的方法。(注意:測試檔案會導入 test-utils.js 而不是直接使用 DOM Testing Library)。

注意

自訂查詢可以透過將 queries 新增至選項設定物件,來新增到 React Testing Libraryrender 方法中。請參閱 render 選項

自訂查詢與自訂 render 方法不同。

test-utils.js
const domTestingLib = require('@testing-library/dom')
const {queryHelpers} = domTestingLib

export const queryByTestId = queryHelpers.queryByAttribute.bind(
null,
'data-test-id',
)
export const queryAllByTestId = queryHelpers.queryAllByAttribute.bind(
null,
'data-test-id',
)

export function getAllByTestId(container, id, ...rest) {
const els = queryAllByTestId(container, id, ...rest)
if (!els.length) {
throw queryHelpers.getElementError(
`Unable to find an element by: [data-test-id="${id}"]`,
container,
)
}
return els
}

export function getByTestId(container, id, ...rest) {
// result >= 1
const result = getAllByTestId(container, id, ...rest)
if (result.length > 1) {
throw queryHelpers.getElementError(
`Found multiple elements with the [data-test-id="${id}"]`,
container,
)
}
return result[0]
}

// re-export with overrides
module.exports = {
...domTestingLib,
getByTestId,
getAllByTestId,
queryByTestId,
queryAllByTestId,
}

buildQueries

buildQueries 輔助函式可讓您使用 testing-library 中的所有標準查詢來建立自訂查詢。

請參閱自訂 render 指南的新增自訂查詢章節,以了解範例用法。

使用其他斷言函式庫

如果您沒有使用 jest,您也許可以為您選擇的函式庫找到類似的自訂斷言集。以下是其他熱門斷言函式庫的 jest-dom 替代方案列表

如果您知道其他替代方案,請發送 Pull Request並在此處新增!

getNodeText

getNodeText(node: HTMLElement)

傳回 HTML 元素的完整文字內容,並移除任何多餘的空白。其目的是將節點中的文字視為使用者在瀏覽器中看到的方式,其中 HTML 程式碼中文字內的任何多餘空白在呈現文字時都沒有意義。

// <div>
// Hello
// World !
// </div>
const text = getNodeText(container.querySelector('div')) // "Hello World !"

當依文字內容查詢節點時,此函式也會在內部使用。這使得 getByTextqueryByText 等函式可以按預期運作,以類似使用者在 DOM 中尋找元素的方式來尋找元素。

此函式對於某些輸入元素具有特殊行為

// <input type="submit" value="Send data" />
// <input type="button" value="Push me" />
const submitText = getNodeText(container.querySelector('input[type=submit]')) // "Send data"
const buttonText = getNodeText(container.querySelector('input[type=button]')) // "Push me"

These elements use the attribute `value` and display its value to the user.