組態選項
簡介
這個函式庫可以透過 configure
函數進行設定,它接受
- 一個純 JS 物件;這將被合併到現有的設定中。例如:
configure({testIdAttribute: 'not-data-testid'})
- 一個函數;該函數將會收到現有的設定,並應返回一個純 JS 物件,它將如上所述進行合併,例如:
configure(existingConfig => ({something: [...existingConfig.something, 'extra value for the something array']}))
注意
像 React Testing Library 這樣的框架特定封裝器可能會在下面顯示的選項中添加更多選項。
- 原生
- React
- Angular
- Cypress
import {configure} from '@testing-library/dom'
import serialize from 'my-custom-dom-serializer'
configure({
testIdAttribute: 'data-my-test-id',
getElementError: (message, container) => {
const customMessage = [message, serialize(container.firstChild)].join(
'\n\n',
)
return new Error(customMessage)
},
})
import {configure} from '@testing-library/react'
configure({testIdAttribute: 'data-my-test-id'})
import {configure} from '@testing-library/angular'
configure({
dom: {
testIdAttribute: 'data-my-test-id',
},
})
import {configure} from '@testing-library/cypress'
configure({testIdAttribute: 'data-my-test-id'})
選項
computedStyleSupportsPseudoElements
如果 window.getComputedStyle
支援偽元素(即第二個參數),則設定為 true
。如果您在瀏覽器中使用 testing-library,您幾乎總是希望將其設定為 true
。只有非常舊的瀏覽器(例如 IE 8 及更早版本)才不支援此屬性。但是,jsdom
目前不支援第二個參數。這包括 jsdom
16.4.0 之前的版本,以及任何在呼叫 getComputedStyle
並帶有第二個參數(例如 window.getComputedStyle(document.createElement('div'), '::after')
)時會記錄 not implemented
警告的版本。預設值為 false
defaultHidden
getByRole
使用的 hidden
選項的預設值。預設值為 false
。
defaultIgnore
getByText
使用的 ignore
選項的預設值。也決定列印錯誤時要忽略的節點。
預設值為 script, style
。
showOriginalStackTrace
預設情況下,waitFor
將確保清除和縮短 Testing Library 擲出的錯誤堆疊追蹤,以便您更容易識別導致錯誤的程式碼部分(非同步堆疊追蹤很難除錯)。如果您想要停用此功能,請將 showOriginalStackTrace
設定為 false
。您也可以在傳遞給 waitFor
的選項中,針對特定呼叫停用此功能。
throwSuggestions
(實驗性)
啟用後,如果存在更好的查詢,測試將會失敗,並提供建議使用的查詢。預設值為 false
。
要針對單個查詢停用建議,只需新增 {suggest:false}
作為選項即可。
screen.getByTestId('foo', {suggest: false}) // will not throw a suggestion
啟用此選項時,它可能會提供缺乏直觀實作的建議。這通常發生在無法命名的角色,最明顯的是段落。例如,如果您嘗試使用 getByText
,您可能會遇到以下錯誤
TestingLibraryElementError: A better query is available, try this:
getByRole('paragraph')
但是,沒有直接的方法可以使用組態物件參數來查詢段落,例如在 getByRole('paragraph', { name: 'Hello World' })
中。
為了解決這個問題,您可以利用自訂函數來驗證元素的結構,如下例所示。更多資訊可以在 GitHub issue 中找到
getByRole('paragraph', {
name: (_, element) => element.textContent === 'Hello world',
})
testIdAttribute
getByTestId
和相關查詢使用的屬性。預設值為 data-testid
。
getElementError
當get 或 find 查詢失敗時,返回錯誤的函數。將錯誤訊息和容器物件作為引數。
asyncUtilTimeout
waitFor
公用程式使用的全域逾時值(以毫秒為單位)。預設值為 1000 毫秒。