跳至主要內容

Cypress 測試函式庫

Cypress 測試函式庫 允許在 Cypress 端對端瀏覽器測試中使用 dom-testing 查詢。

npm install --save-dev cypress @testing-library/cypress

用法

Cypress 測試函式庫 擴展了 Cypress 的 cy 命令。

將此行加入您專案的 cypress/support/commands.js

import '@testing-library/cypress/add-commands'

現在您可以從全域 cy 物件使用 DOM 測試函式庫 的某些 findByfindAllBy 命令。 請參閱 關於查詢 文件以供參考

注意:不支援 get* 查詢,因為對於合理的 Cypress 測試,您需要重試能力,而 find* 查詢已經支援這一點。自 v5 起,query* 查詢不再必要,並將在 v6 中移除。 find* 完全支援內建的 Cypress 斷言(移除了 query* 的唯一用例)。

搭配 TypeScript

應在 tsconfig.json 中按如下方式新增類型定義

{
"compilerOptions": {
"types": ["cypress", "@testing-library/cypress"]
}
}

您可以在 此處找到所有函式庫定義

範例

為了展示一些簡單的範例(來自 cypress/integration/find.spec.js

cy.findByRole('button', {name: /Jackie Chan/i}).click()
cy.findByRole('button', {name: /Button Text/i}).should('exist')
cy.findByRole('button', {name: /Non-existing Button Text/i}).should('not.exist')
cy.findByLabelText(/Label text/i, {timeout: 7000}).should('exist')

// findByRole _inside_ a form element
cy.get('form')
.findByRole('button', {name: /Button Text/i})
.should('exist')
cy.findByRole('dialog').within(() => {
cy.findByRole('button', {name: /confirm/i})
})

Cypress 測試函式庫 同時支援 jQuery 元素和 DOM 節點。這是必要的,因為 Cypress 使用 jQuery 元素,而 DOM 測試函式庫 則需要 DOM 節點。當您傳遞 jQuery 元素作為 container 時,它會從集合中取得第一個 DOM 節點,並將其用作 DOM 測試函式庫 函式的 container 參數。