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

以编程方式调用Cucumber时如何配置生成JSON报告?

如何通过Cucumber编程式调用配置JSON报告生成?

我正在将代码迁移为以编程方式使用Cucumber,但目前找不到配置生成JSON报告的方法。

此前的命令行调用代码如下:

const cucumberPath = require.resolve(".bin/cucumber-js")
const cucumberConfigPath = path.join(cwd, <config file path>)
writeCucumberConfigFile(cucumberConfigPath, cucumber_config)
execSync(
    `npx ${cucumberPath} --config ${constants.testRunnerConfigFiles.cucumberConfigFile} -f json:${reportDir}/${reportFilename}`, {
        encoding: "utf8",
        stdio: "inherit" }
)

参考Cucumber官方编程式调用指南后,改写为以下代码,执行正常但缺失JSON报告生成功能:

const cucumberAPI = require.resolve("@cucumber/cucumber/api")
const { loadConfiguration, loadSupport, runCucumber } = await import(cucumberAPI)
const cucumberConfigPath = path.join(cwd, <path to config>)
writeCucumberConfigFile(cucumberConfigPath, cucumber_config)
const { runConfiguration } = await loadConfiguration({ file: constants.testRunnerConfigFiles.cucumberConfigFile })
const support = await loadSupport(runConfiguration)
await runCucumber({ ...runConfiguration, support })

需要配置JSON报告路径,生成供multiple-cucumber-html-reporter使用的JSON报告文件。


你需要在runConfiguration中添加formatters配置项,指定JSON格式的输出路径。具体修改如下:

const cucumberAPI = require.resolve("@cucumber/cucumber/api")
const { loadConfiguration, loadSupport, runCucumber } = await import(cucumberAPI)
const cucumberConfigPath = path.join(cwd, <path to config>)
writeCucumberConfigFile(cucumberConfigPath, cucumber_config)
const { runConfiguration } = await loadConfiguration({ file: constants.testRunnerConfigFiles.cucumberConfigFile })

// 添加JSON报告配置
runConfiguration.formatters = [
  {
    type: 'json',
    path: `${reportDir}/${reportFilename}` // 替换为你的报告路径
  }
]

const support = await loadSupport(runConfiguration)
await runCucumber({ ...runConfiguration, support })

如果原有配置文件中已经定义了其他格式,可通过数组追加的方式避免覆盖原有配置:

runConfiguration.formatters = [
  ...(runConfiguration.formatters || []),
  { type: 'json', path: `${reportDir}/${reportFilename}` }
]

配置完成后,Cucumber运行时会自动生成指定路径的JSON报告,可直接供multiple-cucumber-html-reporter使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:53:19