Path mapping with typescript doesn't work with cucumber test runner

帅比萌擦擦* 提交于 2019-12-12 19:17:41

问题


When running cucumber-js with my typescript project, path remapping fails. Using relative paths is fine but unforgivably ugly. E.g. import ... from "@src/..." fails, while import ... from "../../../foo.ts" works fine.

My project looks something like this:

package.json
tsconfig.json
src/
  **/*.ts

Inside tsconfig.json, I specify remap paths:

  "paths": {
    "@src/*": [
      "src/*"
    ],
    "*": [
      "node_modules/*",
      "src/types/*"
    ]

My commandline looks like this:

cucumber-js 'src/**/*.feature' --require-module ts-node/register --require 'src/**/*.steps.ts' --format-options '{"snippetInterface": "async-await"}' --format json:reports/cucumber-report.json --format summary --logLevel=error 

And the stacktrace:

Error: Cannot find module '@src/context/Bar'
  at Function.Module._resolveFilename (module.js:513:15)
  at Function.Module._load (module.js:463:25)
  at Module.require (module.js:556:17)
  at require (internal/module.js:11:18)
  at Object.<anonymous> (.../foo.steps.ts:4:1)
  at Module._compile (module.js:612:30)
  at Module.m._compile (.../node_modules/ts-node/src/index.ts:414:23)
  at Module._extensions..js (module.js:623:10)
  at Object.require.extensions.(anonymous function) [as .ts] (.../node_modules/ts-node/src/index.ts:417:12)
  at Module.load (module.js:531:32)
  at tryModuleLoad (module.js:494:12)
  at Function.Module._load (module.js:486:3)
  at Module.require (module.js:556:17)
  at require (internal/module.js:11:18)
  at supportCodePaths.forEach.codePath (.../node_modules/cucumber/lib/cli/index.js:142:42)

The path mapping simply isn't working in this context – cucumber-js specifically. What am I doing wrong? I've shuffled the CLI args, files, no luck. Help... please?


回答1:


There was nothing wrong with the project, but cucumber was unaware of the path mapping mechanism, as --require-module ts-node/register provides language bindings, but not the necessary path resolution intelligence.

For that you need: --require-module tsconfig-paths/register

Install tsconfig-paths

npm install --save-dev tsconfig-paths

Register the module

./node_modules/.bin/cucumber-js ... \
   --require-module ts-node/register \
   --require-module tsconfig-paths/register \
   ...

Then, experience glorious test success!



来源:https://stackoverflow.com/questions/55799604/path-mapping-with-typescript-doesnt-work-with-cucumber-test-runner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!