Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 209
Nino Walker Avatar asked Apr 22 '19 18:04

Nino Walker


1 Answers

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!

like image 110
Nino Walker Avatar answered Nov 15 '22 07:11

Nino Walker