Search code examples
javascripttypescriptcucumberwebstormcucumberjs

How can I use WebStorm to create a Cucumber step definition file in TypeScript instead of JavaScript?


I'm building a new e2e test suite using Cucumber.js and I'd like to use TypeScript for my step files. When I create a new step and I press Alt+Enter to have WebStorm generate a new step file the only option I am presented with is to create a JavaScript file.enter image description here

Does anyone know how I can make this create a new step file in TypeScript?


Solution

  • Webstorm doesn't seem to provide a wizard for file type "TypeScript" so you might want to create your step definition file manually.

    For the Simple Math Example a possible TS step definition file might look like this:

    import * as cucumber from "cucumber";
    
    module.exports = function () {
        // Assign this to a typed variable so we have type-safe access
        let sd: cucumber.StepDefinitions = this;
    
        // The common variable is simply kept in function scope here
        let variable: number = 0;
    
        sd.Given(/^a variable set to (\d+)$/, (value: string) => {
            variable = parseInt(value);
        });
    
        sd.When(/^I increment the variable by (\d+)$/, (value: string) => {
            variable += parseInt(value);
        });
    
        sd.Then(/^the variable should contain (\d+)$/, (value: string) => {
            if (variable != parseInt(value))
                throw new Error('Variable should contain '+value
                              + ' but it contains ' + variable + '.');
        });
    };
    

    Put this content in e.g. features/step_definitions/mathSteps.ts and paste the feature code from the example into a file called e.g. features/math.feature and you should have a running example.