As discussed in previous posts here and here, we use Cypress for writing tests to validate GUI and API tests. In many companies we use behaviour driven development practises where the requirements or acceptance criteria are specified in Gherkin format. As a results, test automation scenarios are also written in Gherkin format. Cucumber , Specflow etc are some of such framework used extensively . In this post, let us examine how we can write BDD test cases in Cypress.
First step is to identify , how we can run Gherkin sytanxed specs with Cypress. This is done with help of cypress-cucumber-preprocessor.
Installation of this package is straight forward
Once NPM package is installed, then next step is to configure Cypress to use it. It consist of 3 main steps.
- Add below code to cypress/package/index.js file.
1 2 3 4 5
- Modify package.json to add below line
1 2 3
nonGlobalStepDefinitions is set as true, which means Cypress Cucumber Preprocessor Style pattern will be used for Step definitions. Default value is false which means old cucumber format of everything global will be used.
There are some other configuration values which we can specify . Details are available in above project documentation link.
- Add support for feature files in cypress.json.
1 2 3
Normally browser is relaunched for each feature files which will result in extended test execution time. cypress-cucumber-preprocessor provides a way to combine all files into a single features file. Above snippet shows that we can expected files named as .feature and .features.
Now it is time to add a feature file. Add a demo.feature file inside Integration/Feature folder. Add below Gherkin into that file
1 2 3 4 5 6 7 8 9 10
Recommended way is to create Step definiton files in a folder named as Feature and keep it inside where we have feature files. Let us create a demosteps.js file.
Location of feature file : Integration/Feature/demo.feature.
Location of StepDefinition : Integration/Feature/demo/demosteps.js
Note: Recommendation from team is to avoid using older way of having Global step definitions defined in cypress/support/step_definitions. More about the rationale for that is available in github documentation. We have specified to use latest style in package.json earlier.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Now run above demo file. This can be done in Cypress UI.
Folder structure is as below