Cypress Testing Library
Cypress Testing Library
允许在Cypress端到端浏览器测
试中使用 dom-testing 查询。
- npm
- Yarn
npm install --save-dev cypress @testing-library/cypress
yarn add --dev cypress @testing-library/cypress
使用
Cypress Testing Library
扩展了 Cypress 的 cy
命令。
在你项目的 cypress/support/commands.js
中添加这一行:
import '@testing-library/cypress/add-commands'
你现在可以使用 DOM Testing Library
' 的所有findBy
, findAllBy
,
queryBy
和queryAllBy
命令,离开全局 cy
对象。请参
阅关于查询的文档以获得参考。
注意:不支持
get*
查询,因为对于合理的 Cypress 测试,你需要重试,而find*
查询已经支持了。query*
查询从 v5 开始就不再支持了,将在 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 Testing Library
同时支持 jQuery 元素和 DOM 节点。这是必要的,因为
Cypress 使用 jQuery 元素,而 Cypress Testing Library
期望 DOM 节点。当你传递一
个 jQuery 元素作为容器时,它将从集合中获得第一个 DOM 节点,并将其作为
DOM Testing Library
函数的 container
参数。