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

如何在ESM(ECMA模块加载器)项目中使用Cucumber?

解决方案

前置条件

  • 确保你安装的是@cucumber/cucumber@8.x及以上版本,低于该版本对ESM的原生支持存在缺陷

配置步骤

  1. 项目模块声明

如果你整个项目都是ESM风格,在根目录package.json中添加配置:

{
  "type": "module"
}

加完后项目内所有.js后缀文件会默认识别为ESM模块,不需要额外使用.mjs后缀。
如果你不想修改全局模块类型,就将步骤文件和你的Application类文件都使用.mjs后缀即可。
2. ### 调整步骤文件写法
把原来CommonJS风格的步骤文件改成ESM导入逻辑,示例如下:

// features/support/steps.js(如果没加全局type:module就用steps.mjs)
import { Given, When, Then } from '@cucumber/cucumber'
import assert from 'node:assert'
// 直接导入你的ESM格式Application类,注意补全实际文件路径
import { Application } from '../../src/app.js'

Given('I start the app', async function () {
  this.app = new Application()
})

When('it is running', async function () {
  // 捕获控制台输出用于后续断言
  this.logContent = ''
  const originalLog = console.log
  console.log = (...args) => {
    this.logContent += args.join(' ')
    originalLog.apply(console, args)
  }
  await this.app.run()
  console.log = originalLog
})

Then('I see the console', function () {
  assert.equal(this.logContent, 'I Ran!')
})
  1. 调整运行命令

不要使用--require-module参数,这个参数是用于预加载模块转换工具(如ts-node)的,不是用来加载步骤定义文件的,直接用原有的--require参数指定步骤文件路径即可:

# 如果是.js后缀的ESM步骤文件
cucumber-js --require features/support/**/*.js

# 如果是.mjs后缀的步骤文件
cucumber-js --require features/support/**/*.mjs

异常排查

如果还是加载失败,可在项目根目录添加cucumber.js(ESM格式)配置文件统一管理配置,无需每次运行传参数:

// cucumber.js
export default {
  require: ['features/support/**/*.js'],
  format: ['pretty']
}

配置完成后直接运行cucumber-js命令即可启动测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:36:05