使用Cypress+Cucumber时单场景失败如何重跑整个feature文件?
Cypress + Cucumber 全Feature文件重试配置方案
Cypress 默认的retries配置仅针对单个测试用例(即单个Cucumber场景)生效,要实现任意场景失败后重跑整个Feature文件,可参考以下两种方案:
方案1:使用cypress-repeat插件(配置简单)
- 先安装依赖:
npm install cypress-repeat -D - 关闭原有cypress配置里的单场景重试参数,避免冲突:
{ "retries": { "runMode": 0, "openMode": 0 } }
- 调整运行命令,指定总运行次数、仅重跑失败的spec文件(每个spec对应一个Feature文件):
示例命令(重试2次,总运行3次):npx cypress-repeat run -n 3 --rerun-failed-only
方案2:自定义钩子实现(无需第三方插件)
如果不想引入额外依赖,可以通过Cypress全局钩子手动标记失败的Feature文件,触发全文件重跑:
- 先在
cypress.config.js中关闭单场景重试,注册重跑任务:
const { defineConfig } = require('cypress') module.exports = defineConfig({ retries: { runMode: 0, openMode: 0 }, e2e: { setupNodeEvents(on, config) { on('task', { 'rerun:spec'(specPath) { const spec = require.resolve(specPath) delete require.cache[spec] return null } }) }, }, })
- 在
cypress/support/e2e.js中添加全局运行状态监听逻辑:
const failedSpecs = new Set() const MAX_RETRIES = 2 // 自定义最大重试次数 before(() => { const specPath = Cypress.spec.relative if (failedSpecs.has(specPath)) { Cypress.env('retryCount', (Cypress.env('retryCount') || 0) + 1) } }) afterEach(() => { if (Cypress.currentTest.state === 'failed') { failedSpecs.add(Cypress.spec.relative) } }) after(() => { const retryCount = Cypress.env('retryCount') || 0 const currentSpec = Cypress.spec if (failedSpecs.has(currentSpec.relative) && retryCount < MAX_RETRIES) { cy.task('rerun:spec', currentSpec.absolute) } })
注意:如果你的项目配置是多个Feature对应同一个spec文件,只需把上述逻辑中的spec路径判断替换为Feature文件路径即可。
内容的提问来源于stack exchange,提问作者Wasfi Nasir
相关产品推荐
相关产品推荐

