Before Spec 事件
before:spec
事件会在运行 spec 文件前触发。当通过 cypress open
运行 Cypress 时,该事件会在浏览器启动时触发。
语法
caution
⚠️ 这段代码属于
setupNodeEvents 函数的一部分,
因此会在 Node 环境中执行。你不能在此函数中调用 Cypress
或 cy
命令,
但可以直接访问文件系统和操作系统的其他部分。
caution
⚠️ 通过 cypress open
运行时,只有在启用 experimentalInteractiveRunEvents 标志 时才会触发 before:spec
事件。
- cypress.config.js 文件
- cypress.config.ts 文件
const { defineConfig } = require('cypress')
module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('before:spec', (spec) => {
/* ... */
})
},
},
})
import { defineConfig } from 'cypress'
export default defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('before:spec', (spec) => {
/* ... */
})
},
},
})
spec (Object)
Spec 文件的详细信息,包含以下属性:
属性 | 描述 |
---|---|
name | spec 文件的基础名称(例如 login.cy.js ) |
relative | spec 文件相对于项目根目录的路径(例如 cypress/e2e/login.cy.js ) |
absolute | spec 文件的绝对路径(例如 /Users/janelane/my-app/cypress/e2e/login.cy.js ) |
用法
你可以从 before:spec
事件处理函数中返回一个 promise,Cypress 会等待该 promise 完成后再继续运行 spec。
在 spec 运行前将相对路径输出到 stdout
- cypress.config.js 文件
- cypress.config.ts 文件
const { defineConfig } = require('cypress')
module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('before:spec', (spec) => {
// spec 对象结构示例:
// {
// name: 'login.cy.js',
// relative: 'cypress/e2e/login.cy.js',
// absolute: '/Users/janelane/app/cypress/e2e/login.cy.js',
// }
console.log('Running', spec.relative)
})
},
},
})
import { defineConfig } from 'cypress'
export default defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('before:spec', (spec) => {
// spec 对象结构示例:
// {
// name: 'login.cy.js',
// relative: 'cypress/e2e/login.cy.js',
// absolute: '/Users/janelane/app/cypress/e2e/login.cy.js',
// }
console.log('Running', spec.relative)
})
},
},
})