Cypress 测试库
Cypress 测试库 允许在 Cypress 端到端浏览器测试中使用 dom-testing 查询。
- npm
- Yarn
npm install --save-dev cypress @testing-library/cypress
yarn add --dev cypress @testing-library/cypress
使用
Cypress 测试库 扩展了 Cypress 的 cy 命令。
将此行添加到您的项目的 cypress/support/commands.js 中
import '@testing-library/cypress/add-commands'
您现在可以使用一些 DOM 测试库 的 findBy 和 findAllBy 命令来执行全局 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 测试库 支持 jQuery 元素和 DOM 节点。这是必要的,因为 Cypress 使用 jQuery 元素,而 DOM 测试库 预期 DOM 节点。当您将 jQuery 元素作为 container 传递时,它将从集合中获取第一个 DOM 节点,并将其用作 DOM 测试库 函数的 container 参数。