Search code examples
typescriptcucumbercucumberjs

Proper usage of cucumber with typescript?


I was following a tutorial but the setup is really bad. Basically it uses typescript to convert .ts files to .js. So basically pollutes your whole source code with .js files around.

So as soon as you import your .ts file from source code, all dependencies are duplicated with a .js file.

Do you know how to do proper typescript cucumber tests?

A hacky solution: Copy all features and all files to another temp folder, run from there. I would expect cucumber to be a bit more mature than this, hence my question here?

Or change the configuration of cucumber to look in the build folder from ts.

Thank you

Why just using typescript won't work:

Code structure:

  • tests
    • a.feature
    • stepDefinitions.ts

Now you will compile the typescript and have this structure:

  • tests
    • a.feature
    • stepDefinitions.ts
  • build
    • tests
      • stepDefinitions.js

Now you can see that stepDefinitions.js has no idea where to find a.feature. If you run cucumber on the build/test folder it won't find any step feature to run... because well, they are in the tests folder. So the hacky way to fix it is to copy over the features files resulting this structure:

  • tests
    • a.feature
    • stepDefinitions.ts
  • build
    • tests
      • a.feature
      • stepDefinitions.js

Now it will work but is hacky, I don't like it.


Solution

  • Updated answer based on more info provided:

    The first thing you should do is separate your features and steps into their own folders

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

    Next, create a cucumber.js file which will be the cucumber profile. I use the following profile but it's up to you what you want to do

        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,
    };
    

    The above tells cucumber where your steps are. Now you can run something like the following from the root of the project

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

    This will

    1. Compile your code
    2. Run the cucumber-js library
    3. Run cucumber-js against the features folder
    4. Run cucumber-js against the features folder with the default profile that you built in your cucumber.js file

    Edit: See https://stackoverflow.com/a/55378059/3323395 for how to do this without needing to compile first