mount
Cypress 没有内置的 cy.mount()
命令。该命令必须在您的支持文件中设置。默认情况下,当您使用 Cypress 配置项目时,系统会自动为您生成一个。
本指南介绍如何自定义 cy.mount()
命令以满足应用程序的需求。
我们建议设置自定义的 cy.mount()
命令,而不是从挂载库中导入 mount 命令。这样做有几个优点:
- 您无需在每个测试中导入 mount 命令,因为
cy.mount()
命令是全局可用的。 - 您可以设置通常在每次测试中需要执行的常见场景,例如将组件包装在 React Provider 中或添加 Vue 插件。
让我们看看如何实现该命令。
创建新的 cy.mount()
命令
不同框架渲染组件的方式不同,因此我们提供了针对特定框架的 mount()
函数,可以通过以下方式导入:
- React
- Vue
- Angular
info
React 用户须知
从 cypress/react 模块导出的 mount()
命令支持标准的 JSX 语法来挂载组件。
import { mount } from 'cypress/react'
info
Vue 用户须知
从 cypress/vue 库导出的 mount()
命令内部使用了 Vue Test Utils,但与在 node 的虚拟浏览器中挂载组件不同,它会在实际浏览器中挂载组件。
import { mount } from 'cypress/vue'
info
Angular 用户须知
从 cypress/angular 库导出的 mount()
命令内部使用了 Angular TestBed,但与在 node 的虚拟浏览器中挂载组件不同,它会在实际浏览器中挂载组件。
import { mount } from 'cypress/angular'
要使用 cy.mount()
,请使用 Cypress.Commands.add()
将 自定义命令 添加到命令文件中。以下是您可以参考的示例命令:
- React
- Vue
- Angular
import { mount } from 'cypress/react'
Cypress.Commands.add('mount', (component, options) => {
// 包装所需的任何父组件
// 例如:return mount(<MyProvider>{component}</MyProvider>, options)
return mount(component, options)
})
import { mount } from 'cypress/vue'
Cypress.Commands.add('mount', (component, options = {}) => {
// 设置 options 对象
options.global = options.global || {}
options.global.stubs = options.global.stubs || {}
options.global.stubs['transition'] = false
options.global.components = options.global.components || {}
options.global.plugins = options.global.plugins || []
/* 添加任何全局插件 */
// options.global.plugins.push({
// install(app) {
// app.use(MyPlugin);
// },
// });
/* 添加任何全局组件 */
// options.global.components['Button'] = Button;
return mount(component, options)
})
import { mount } from 'cypress/angular'
Cypress.Commands.add('mount', (component, config) => {
return mount(component, config)
})
为 cy.mount()
命令添加 TypeScript 类型定义
在使用 TypeScript 时,您需要为自定义命令添加类型定义,以获取代码补全并避免任何 TypeScript 错误。
类型定义需要放在任何代码都可以访问的位置,因此我们建议在根目录中创建一个 cypress.d.ts
文件,并使用以下示例作为自定义命令的起点:
- React
- Vue
- Angular
import { mount } from 'cypress/react'
declare global {
namespace Cypress {
interface Chainable {
mount: typeof mount
}
}
}
import { mount } from 'cypress/vue'
type MountParams = Parameters<typeof mount>
type OptionsParam = MountParams[1]
declare global {
namespace Cypress {
interface Chainable {
mount: typeof mount
}
}
}
import { mount } from 'cypress/angular'
declare global {
namespace Cypress {
interface Chainable {
mount: typeof mount
}
}
}
如果您的测试无法找到自定义命令的类型,请手动将 cypress.d.ts
文件包含到所有 tsconfig.json
文件中,如下所示:
"include": ["./src", "cypress.d.ts"]