黄瓜与打字稿的正确用法?

Proper usage of cucumber with typescript?

我正在关注一个 tutorial 但设置真的很糟糕。基本上它使用打字稿将 .ts 文件转换为 .js。所以基本上用 .js 文件污染了你的整个源代码。

因此,一旦您从源代码导入 .ts 文件,所有依赖项都会与 .js 文件一起复制。

你知道如何进行正确的打字稿黄瓜测试吗?

一个 hacky 解决方案:将所有功能和所有文件复制到另一个临时文件夹,运行 从那里。我希望黄瓜比这成熟一点,所以我的问题在这里?

或者更改 cucumber 的配置以在 ts 的构建文件夹中查找。

谢谢

为什么只使用打字稿行不通:

代码结构:

现在你将编译打字稿并具有以下结构:

现在您可以看到 stepDefinitions.js 不知道在哪里可以找到 a.feature。如果你在 build/test 文件夹中 运行 黄瓜,它不会找到 运行 的任何步骤功能......因为好吧,它们在测试文件夹中。所以修复它的 hacky 方法是复制生成此结构的功能文件:

现在可以用了,但是有点笨拙,我不喜欢。

我没有关注你的问题? Cucumber 与将 .ts 文件编译为 .js 文件无关,这是 typescript 做的。如果您不希望 .ts 和 .js 文件位于同一文件夹中,则可以将以下内容添加到 tsconfig.json 文件中。

"outDir": "typeScript"

这会将 javascript 文件输出到项目根目录下的文件夹 "typeScript"。我个人喜欢将它们放在一起,因为这样更容易调试。无法摆脱正在创建的 .js 文件,因为它们是 运行 javascript.

时使用的文件

根据提供的更多信息更新了答案:

您应该做的第一件事是将您的功能和步骤分离到它们自己的文件夹中

 tests
  features
    a.feature
    b.feature
  stepDefinitions
    aStep.ts

接下来,创建一个 cucumber.js 文件,这将是黄瓜配置文件。我使用以下配置文件,但这取决于你想做什么

    var common = [
  `--format ${
    process.env.CI || !process.stdout.isTTY ? 'progress' : 'progress-bar'
    }`,
  '--format json:./reports/cucumber-json-reports/report.json',
  '--format rerun:@rerun.txt',
  '--format usage:usage.txt',
  '--parallel 20',
  '--require ./build/tests/stepDefinitions/**/*.js',
  '--require ./build/tests/stepDefinitions/*.js',
  '--require ./build/tests/support/*.js'
].join(' ');

module.exports = {
  default: common,
};

上面的内容告诉黄瓜你的脚步在哪里。现在你可以 运行 从项目的根目录中 运行 像下面这样的东西

tsc && ./node_modules/.bin/cucumber-js ./tests/features/ -p default

这将

  1. 编译你的代码
  2. 运行 cucumber-js 库
  3. 运行 cucumber-js 针对功能文件夹
  4. 运行 cucumber-js 使用您在 cucumber.js 文件中构建的默认配置文件

编辑:请参阅 了解如何在不需要先编译的情况下执行此操作

您不需要按照 Raymond Kelly 的建议,使用 tsc 编译代码,然后在编译文件上使用 运行 cucumber。你可以 运行 黄瓜与使用 --require-module ts-node/register 的打字稿转译器。完整示例由 hdorgeval 在 cucumber-ts-starter

提供

编辑:提到的原始模板已在新版本中得到改进 cucumber7-ts-starter

将黄瓜测试放在 src 中并用 tsc 编译它并不是一个很好的做法,因为它污染了 build 软件不需要的目录 运行,尤其是生产中。

可以使用 ts-node。 运行npm install ts-node --save-dev。这是 cucumber-js 配置文件的示例(所有 .feature 和步骤定义文件都在我的设置中的 /features 文件夹中):

module.exports = {
  default: [
    '--require-module ts-node/register',
    '--require ./features/**/*.ts',
    '--require ./features/*.ts',
  ].join(' '),
};

您还可以使用 ts-node 模块来编译您的 cucumber steps.ts 文件,因此您不需要 generate.js 文件

例如

./node_modules/.bin/cucumber-js features --require step-definitions/*.ts  --require-module ts-node/register --format node_modules/cucumber-pretty"