You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在cypress-cucumber-preprocessor中捕获场景运行结果及名称?

解决方案:在cypress-cucumber-preprocessor中捕获场景名称与运行结果

方案一:使用官方钩子(推荐)

cypress-cucumber-preprocessor提供了专门的场景生命周期钩子,你可以在cypress/support/e2e.js(或.ts文件)中配置After钩子,直接获取场景信息和运行结果:

import { After } from "@badeball/cypress-cucumber-preprocessor";

After(function (scenario) {
  // 获取场景名称
  const scenarioName = scenario.pickle.name;
  // 获取运行结果(可选值:passed/failed/skipped等)
  const scenarioStatus = scenario.result?.status;
  
  // 此处可执行自定义逻辑,比如上报结果、写入日志等
  console.log(`场景"${scenarioName}"运行结果:${scenarioStatus}`);
});

如果是TypeScript项目,为避免类型报错,可添加全局类型声明:

declare global {
  namespace Cypress {
    interface Scenario {
      pickle: { name: string };
      result?: { status: string };
    }
  }
}

方案二:修改预处理器源码(不推荐,升级会失效)

针对你提到的修改lib/createTestFromScenario.js中runTest()方法的方案,添加Cypress.env('currentScenario', scenario)后,可结合Cypress原生的afterEach钩子获取运行结果:

  1. 按描述修改预处理器源码,将场景信息存入Cypress环境变量
  2. 在cypress/support/e2e.js中添加如下代码:
afterEach(function () {
  const currentScenario = Cypress.env('currentScenario');
  // 通过Cypress原生API获取测试状态
  const testStatus = this.currentTest.state; // 可选值:passed/failed/pending等
  
  if (currentScenario) {
    console.log(`场景"${currentScenario.pickle.name}"运行结果:${testStatus}`);
  }
});

注意:此方法需在预处理器升级后重新修改源码,维护成本高,仅作为临时替代方案。

关于window.testState.currentScenario的问题

该变量属于非官方内部实现,稳定性无法保证,不建议依赖。若临时使用,可在TypeScript中添加类型声明解决报错:

declare global {
  interface Window {
    testState?: { currentScenario: { pickle: { name: string } } };
  }
}

内容的提问来源于stack exchange,提问作者Sagarika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:25:05