Tired of spending hours writing and maintaining complex test scripts? We get it. That’s why we’re excited to introduce the Cypress Cucumber Framework (Cypress BDD Automation) — a game changer for software testing. This combination makes testing more efficient, collaborative, and accessible.  

Imagine a framework that speaks everyone’s language, from developers to product managers. With Cypress, Cucumber, and Behavior-Driven Development (BDD), you can therefore achieve tests that are robust, reliable, and easily understood. No more cryptic code or miscommunication!  

In this post, we will first cover the fundamentals of Cypress and Cucumber BDD, then guide you through the setup process, and finally share best practices for automation. Get ready to boost productivity and streamline your testing!

Index

  • About Cypress  
  • About Cucumber (BDD)  
  • Installation Cucumber  
  • Create Feature and Spec File   
  • Configure feature file and step definition path   
  • Execute Script   
  • How to run Cypress Cucumber tests using Tags  

In our last blog post, JavaScript and Cypress Framework for Modern UI Automation, we explored essential aspects of UI automation with Cypress. Here’s a recap of what we covered: 

  • Introduction to Cypress 
  • Setting Up Cypress 
  • Writing Effective Tests 
  • Debugging with Cypress 
  • Best Practices 
  • Real-World Examples

By the end, readers will have gained a strong foundation in Cypress for UI automation, making them ready to implement effective automated testing in their projects.

In the current blog on the Cypress Cucumber Framework: A Complete Guide to BDD Automation for Efficient Testing, we will build upon this knowledge by integrating Cucumber for Behavior-Driven Development, enhancing test readability and collaboration among team members. 

What is Behavior Driven Development (BDD)? 

Behavior Driven Development (BDD) is an agile software development practice that enhances communication between stakeholders. It, in turn, encourages collaboration among developers, testers, and non-technical team members to define how an application should behave, all based on user requirements. The core philosophy is to define behavior in plain language, making it easily understandable for all parties involved.

What is Cucumber?

Cucumber is an open-source tool that supports BDD by allowing users to write tests in plain language. It, moreover, uses a domain-specific language (DSL) called Gherkin, which is designed to be human-readable. As a result, this means that even non-technical stakeholders can participate in the testing process, enhancing collaboration and ensuring that everyone is on the same page.

Key Features of Cucumber BDD 

  • Readable Syntax: Cucumber uses Gherkin syntax, enabling test scenarios to be written in natural language. Each scenario follows the structure: 
    • Given: Sets pre-conditions or context. 
    • When: Specifies the user’s action. 
    • Then: Defines the expected outcome. 
  • Collaboration: Cucumber promotes teamwork by providing a common language, and reducing miscommunications between developers and stakeholders. 
  • Automation Support: Integrates well with tools like Selenium, making it easier to automate tests based on defined behaviors. 
  • CI/CD Integration: Cucumber can be seamlessly added to CI/CD pipelines, supporting automated testing and ensuring code quality throughout development.

Benefits of Using Cucumber BDD 

  • Improved Communication: Encourages collaboration among all stakeholders, reducing misunderstandings. 
  • Higher Test Coverage: Ensures that all user scenarios are considered by involving non-technical team members. 
  • Living Documentation: Keeps documentation relevant and up to date with evolving application features. 
  • Faster Feedback Loop: Automated tests provide quick feedback, accelerating development and iterations. 

How to Get Started with Cucumber BDD 

  1. Set Up Your Environment 
  2. Define Features and Scenarios 
  3. Map Step Definitions 
  4. Write Script 
  5. Run Tests 

Benefits of combining Cypress with Cucumber (Cypress Cucumber Framework)

While Cypress is powerful on its own, combining it with Cucumber takes our testing to a whole new level. Cucumber is a tool that supports Behavior-Driven Development (BDD), allowing us to write tests in a natural language that both technical and non-technical team members can understand. 

Here are some key benefits of this combination: 

  • Improved collaboration: By using Cucumber’s Gherkin syntax, we create a common language between developers, QA, and business stakeholders. 
  • Enhanced test readability: Cucumber scenarios are written in plain English, making it easier for everyone to understand what’s being tested. 
  • Reusable step definitions: We can create step definitions in Cypress that map to Cucumber scenarios, promoting code reuse and maintainability. 
  • Living documentation: Our Cucumber features serve as both tests and documentation, ensuring our documentation stays up to date with the actual product behavior. 
  • Scenario-driven development: We can focus on describing the desired behavior first, then implement the necessary code to make it work.

Here’s a comparison of traditional testing approaches versus BDD: 

Aspect Traditional Testing Behavior-Driven Development (BDD) 
Focus Verifying functionality Describing user behavior 
Language Technical jargon Natural language 
Collaboration Limited to developers and testers Extensive involvement of all stakeholders 
Documentation Separate from tests Tests double as documentation 
Test Creation After development Before or during development 
User Involvement Minimal Continuous involvement 
Feedback Cycle Slower feedback Rapid feedback loops 

In the next phase of our exploration of the Cypress Cucumber Framework, we’ll learn the practicalities of setup and implementation. We’ll cover how to structure projects, write effective scenarios, and harness the strengths of both Cypress and Cucumber to build a comprehensive, maintainable test suite.

Cypress Cucumber Framework Folder Structure 

When building a robust test automation framework with Cypress and Cucumber, the project structure plays a critical role in maintainability, scalability, and team collaboration. A well-organized project allows testers and developers to easily locate files, add new features, and scale the framework as the project grows. Here’s a suggested structure for setting up your Cypress Cucumber framework:

Breakdown of the Structure:

cypress/ – This is the main directory where all Cypress-related files are stored. It houses everything from test data to plugins and supporting scripts. 

e2e/features/ – This is where our .feature files, written in Gherkin syntax are stored. Each .feature file describes test scenarios in a human-readable format, enabling BDD-style testing. 
For example: – Login.feature 

e2e/step_definitions/ – This subfolder holds our JavaScript files where we define the actual step definitions corresponding to the steps in our .feature files. 
For example: – Login_steps.js 

e2e/page_objects/ – This is a new folder for Page Object Model (POM) files. Page objects abstract the logic of interacting with different pages in our application. This separation keeps your tests clean, readable, and easier to maintain. 

cypress.config.js – This configuration file allows us to manage and configure our Cypress environment. Here, we can set environment-specific configurations, manage base URLs, and define other test-related settings. 

package.json – This is the standard Node.js configuration file. It lists the dependencies, scripts, and other essential settings needed for your Cypress Cucumber project. Here, we’ll define the testing dependencies like cypress, cypress-cucumber-preprocessor, and any other required libraries. 

Based on the folder structure outlined above, let’s now proceed to create the structure in our project. 

Setting Up the Automation Framework 

Now we’ve covered the basics of Cypress and Cucumber BDD, let’s dive into setting up our automation framework. This crucial step will lay the foundation for our entire testing process, ensuring we have a robust and efficient system in place. 

Install VS Code and create new project 

Install & configure Cypress Automation Framework 

To set up the Cypress Cucumber framework, the first step is to install Visual Studio Code (VS Code) and set up a basic Cypress JavaScript framework. I’ve outlined the detailed procedure for installing Cypress and creating the initial Cypress framework in my previous blog, JavaScript and Cypress Framework for Modern UI Automation. You can follow the steps from that guide to get your Cypress framework up and running. Once that’s done, we’ll move forward with installing and integrating Cucumber BDD in our project. We can also clone cypress framework from “JavaScript-Cypress-WebAutomation” repository. 

By following the steps outlined in the JavaScript and Cypress Framework for Modern UI Automation blog, we’ll now have a complete Cypress framework set up, including the package.json, cypress.config.js, and a cypress folder containing your tests, test data, and hooks. The next step is to upgrade this existing Cypress framework to a Cypress Cucumber framework for BDD integration.

Install Cucumber 

To install Cucumber, we have to install @badeball/cypress-cucumber-preprocessor dependency version 13.0.2. 

@badeball/cypress-cucumber-preprocessor is a plugin that enables the use of Cucumber’s Behavior Driven Development (BDD) approach in Cypress testing. It allows you to write tests in Gherkin syntax (using feature files), making it easier to define scenarios in plain language that non-technical stakeholders can understand. This preprocessor translates Gherkin steps into Cypress commands, allowing smooth integration of BDD into your Cypress test suite. 

Open the terminal in VS Code, verify the project path, and run the following command to install @badeball/cypress-cucumber-preprocessor.

npm install @badeball/cypress-cucumber-preprocessor@13.0.2

Now we must install @cypress/browserify-preprocessor dependency.

@cypress/browserify-preprocessor is a plugin for Cypress that bundles JavaScript files using Browserify. It processes the files before Cypress executes them, allowing you to use CommonJS modules and other advanced JavaScript features in your test files. This preprocessor helps Cypress understand and run tests that include modern JavaScript or require module bundling, ensuring smooth execution of your test suite. 

Command to install @cypress/browserify-preprocessor 

npm install –save-dev @cypress/browserify-preprocessor 

Configuring Installed Dependencies in cypress.config.js 

When we install Cypress, the cypress.config.js file is automatically created at the root of our project. To configure Cypress with Cucumber, we need to add the following code to this file: 

This configuration in the cypress.config.js file is required to enable the Cypress Cucumber Preprocessor and handle feature files written in Gherkin syntax. 

  • const preprocessor = require(“@badeball/cypress-cucumber-preprocessor”); 
    const browserify = require(“@badeball/cypress-cucumber-preprocessor/browserify”);
     
  • These imports load the necessary preprocessor libraries to translate Gherkin syntax into Cypress test commands. 
  • preprocessor.addCucumberPreprocessorPlugin: Adds Cucumber-specific functionalities, such as generating JSON reports after test runs. 
  • on(“file:preprocessor”, browserify.default(config)): Uses Browserify to bundle the test files, ensuring the feature files and JavaScript modules are correctly processed before execution. 

In summary, this configuration integrates the Cucumber framework with Cypress and ensures that feature files are preprocessed and executed correctly.

Hooks 

Hooks are functions that allow you to run specific code before or after a scenario or feature in your Cucumber tests. These hooks help manage setup and teardown tasks, such as navigating to a webpage or resetting application state, before or after each test is executed. 

Types of Hooks:  
Before: Runs before each scenario.
After: Runs after each scenario. 
BeforeAll: Runs once before all scenarios in a feature. 
AfterAll: Runs once after all scenarios in a feature. 

Before HookThis code runs before each scenario in the feature file. It navigates to the https://www.calculator.net website using the cy.visit() command. This ensures that every test starts from the calculator page. 

After Hook This code runs after each scenario. It clicks on the cancel button (specified in the Selectors.json file) to potentially reset any changes made during the test, ensuring a clean state for subsequent tests. 

These hooks help ensure consistency and better test management by handling common setup and cleanup tasks efficiently. 

Automating Scenario 

Creating  .Feature File 

Before we begin creating the .feature file, let’s outline the functionalities we’ll be automating. We’ll be working with the Calculator.net web application, focusing on automating basic arithmetic operations: addition, subtraction, multiplication, and division. 

Test Scenarios: 

  1. Verify user can perform addition 
  2. Verify user can perform subtraction 
  3. Verify user can perform multiplication 
  4. Verify user can perform division 

Now we will follow below steps and create feature file 

  • Launch Visual Studio Code and open your project folder. 
  • Navigate to cypress/e2e create feature directory. 
  • Right-click on the feature folder and select New File.  
    – Name the file with the .feature extension, e.g., calculator.feature
  • Write below code in calculator.feature with the Gherkin Syntax

What is a Feature File?

A feature file is a document written in plain language that outlines the behavior of a software feature or a set of related features. It is primarily used in Behavior Driven Development (BDD) frameworks like Cucumber to describe application behavior in a way that both technical and non-technical stakeholders can understand. 

The structure of a feature file includes: 

  1. Feature 
  2. Scenario 
  3. Given-When-Then format 

Feature files use the Gherkin language to describe these behaviors. 

What is Gherkin?

Gherkin is a structured language used to write feature files in BDD. It uses simple syntax and plain English, making it easy for anyone, including non-developers, to understand the application’s expected behavior. Gherkin uses a specific set of keywords to define the structure of a feature file, including: 

  • Feature: A high-level description of the functionality being tested. 
  • Scenario: Individual test cases written to validate specific aspects of the feature. 
  • Given: Describes the initial context or prerequisites (e.g., navigating to a webpage). 
  • When: Specifies the action taken by the user or system (e.g., clicking a button). 
  • Then: Describes the expected outcome (e.g., the result should be displayed). 
  • And / But: Used to add additional steps to the scenario.

Gherkin’s key advantage is its readability and collaboration, as it helps bridge the communication gap between technical teams and non-technical stakeholders by providing a shared language for defining requirements. 

Creating Step Definition file

In a Cypress project using @badeball/cypress-cucumber-preprocessor, feature file steps written in plain English are mapped to corresponding code in the step definition file. This mapping is crucial because it connects the behavioral steps defined in the feature file to the automation code that performs the actual actions and validations. 

Now we will create step file and map with feature file 

  • Open project in VS code. 
  • Navigate to cypress/e2e. Right click on e2e and select New Folder and give name as “step_definition“. 
  • Right-click on the step_definition  folder and select New File.  
    – Name the file with the .js extension, e.g. CalculatorStep.js

Let’s now break down how this mapping works using the provided example: 

The step_definition file contains JavaScript functions that implement the logic for each feature file step. These functions are mapped to the feature file steps based on matching text patterns

Mapping Example: 

  • Feature Step: When User clicks on number “2” 
  • Step Definition:
  • The text “User clicks on number {string}” matches the feature step text, where {string} is a placeholder for the number (“2” in this case). 
    • The value “2” is passed as the number parameter to the function calculatorPage.clickNumber(number). 
  • Feature Step: Then The result should be “3” 
  • Step Definition: 
  • The text “The result should be {string}” matches the step, and “3” is passed as the expectedResult parameter to verifyResult. 

Dynamic Parameter Handling

The placeholders in the step definition {string} allow dynamic values from the feature file to be passed as parameters. This approach ensures that the same step definition can handle multiple scenarios with different inputs, making your tests more reusable. 

Behind the Scenes: Automatic Mapping

The @badeball/cypress-cucumber-preprocessor automatically matches feature file steps to step definitions based on the matching text. As long as: 

  • The text pattern in the step definition matches the feature file step. 
  • The corresponding file is in the correct folder structure (e.g., step_definition)

We don’t need to do any additional configuration. 

Why This Mapping is Useful 

  • Readability: The feature file is easy to understand for non-technical stakeholders. 
  • Reusability: A single step definition can be reused across multiple scenarios with different inputs. 
  • Separation of Concerns: Keeps business logic (feature file) separate from automation code (step definitions). 

Creating Page file 

What is a Page Object Model (POM) File? 

The Page Object Model (POM) is a design pattern in test automation that promotes the separation of test logic from the UI elements. It creates an object repository for web UI elements, making tests more maintainable, readable, and reusable. Each page of the application is represented by a corresponding class, which contains methods to interact with the elements on that page. 

Benefits of Using POM: 

  • Maintainability: Changes in UI require updates in only one place (the POM). 
  • Readability: Tests are cleaner and more understandable. 
  • Reusability: Common methods can be reused across different test cases. 

Now let’s create Page Object Model (POM) file, 

  • Open project in VS code. 
  • Navigate to cypress/e2e Right click on e2e and select New Folder and give name as “page“. 
  • Right-click on the page folder and select New File.  
    – Name the file with the .js extension, e.g., CalculatorPage.js

The CalculatorPage class uses the Page Object Model (POM) to manage interactions with a calculator’s UI. 

  1. Selectors Import
    • Fetches locators from Selectors.json  for buttons and result display. 
  2. Methods
    • clickNumber(number): Clicks a number button (e.g., “2” clicks selectors.twoNumberButton). 
    • clickOperator(operator): Clicks an operator button (+, -, *, /). 
    • clickEquals(): Clicks the “=” button. 
    • verifyResult(expectedResult): Validates the displayed result matches with the expected value. 

Configuring Feature and Step Definition Paths 

To seamlessly integrate feature files and step definitions in our Cypress project using the Cucumber preprocessor, we need to configure their paths. Here’s how we can set them up effectively: 

Defining the Feature File Path and additional configuration 

Start by defining where your feature files are located: 

  1. Open cypress.config.js
  2. Under the e2e section in module.exports, specify the path to your feature files and additional configuration. 

Final cypress.config.js file look as below 

breakdown of the configurations in our cypress.config.js file: 

  • specPattern: Specifies the location and format of test files .feature in the cypress/e2e directory, supporting Gherkin syntax. 
  • downloadsFolder: Custom folder path cypress/downloads for files downloaded during tests. 
  • screenshotsFolder: Specifies the folder cypress/screenshots where screenshots will be saved. 
  • viewportWidth and viewportHeight: Sets the browser’s default viewport size to 1920×1080 pixels
  • Timeouts
    • execTimeout: Maximum time (10 seconds) allowed for the execution of Cypress commands. 
    • pageLoadTimeout: Maximum time (18 seconds) to wait for page load events. 
    • defaultCommandTimeout: Maximum time (10 seconds) for Cypress commands to complete. 
  • screenshotOnRunFailure: Takes a screenshot automatically if a test fails true
  • chromeWebSecurity: Disables Chrome’s web security to allow testing across different origins (false). 
  • trashAssetsBeforeRuns: Cleans up previous test assets (like screenshots and videos) before each test runs (true). 
  • experimentalModifyObstructiveThirdPartyCode: Enables experimental support for modifying third-party scripts to improve compatibility (true). 

By configuring these paths, Cypress knows where to find and execute your feature files during test runs. 

Setting Up the Step Definition Path 

Next, configure the path to your step_definition files in the package.json file: 

  1. Open the package.json file in your Cypress project. 
  2. Add or edit the cypress-cucumber-preprocessor section to include the path for step definitions. 

Final package.js looks as below 

package.json defines the setup for a Cypress framework with Cucumber integration for Behavior-Driven Development (BDD). Let’s breakdown: 

  1. Metadata
    • name: “cypresscucumberframework” – The name of the project. 
    • version: Version of the framework. 
    • description: Describes the purpose of the project as a Cypress BDD framework using Cucumber. 
    • author: The author of the project. 
    • license: The license type. 
    • keywords: A list of relevant keywords to describe the project. 
  2. Dependencies: 
    • @badeball/cypress-cucumber-preprocessor: Used for integrating Cucumber feature files with Cypress. 
    • cypress: Core Cypress testing library. 
  3. Dev Dependencies: 
    • @cypress/browserify-preprocessor: Required to handle JavaScript files with Cucumber preprocessor. 
  4. Cypress Cucumber Preprocessor Configuration: 
    • stepDefinitions: Specifies the path for step definition files (cypress/e2e/step-definition/*.js)
    • filterSpecs: Ensures only filtered specs (by tags) are run. 
    • omitFiltered: Omits filtered tests from output results. 

This ensures the Cucumber preprocessor can locate and execute the step definitions during testing.

Execute Test Cases in Cypress 

Running Cypress Tests via Cypress Runner 

  1. Open VS Code terminal and type: 
    • npx cypress open 
  2. The Cypress Runner will launch. 
  3. Select E2E Testing, then choose your desired browser. 
  4. A dashboard will appear with all feature files listed. Select a feature file to start execution.
Cypress Cucumber Framewrok

Pro Tip: To run all test suites in one go instead of selecting them individually: 

  • Edit package.json file under the “scripts” section as shown: 

“scripts”: { 
  “script”: “cypress run –browser chrome”, 
  “test”: “npm run script” 

  • Now, execute the tests with: 

npm run test 

This command runs all tests in headless mode using Chrome. You can switch browsers if needed and even add pre-test or post-test configurations, like cleaning reports or screenshots. 

Running Cypress Cucumber Tests with Tags 

We can filter tests by tagging scenarios, such as @smoke, @sanity, or @regression. Here’s how: 

  1. Run specific tests by tag 

npx cypress run –env tags=”@regression” 

Ensure these settings are added under “cypress-cucumber-preprocessor” in package.json: 

“filterSpecs”: true, 
“omitFiltered”: true 

  1. Run tests with either of two tags 

npx cypress run –env tags=”@Smoke or @regression” 

  1. Run tests with both tags 

npx cypress run –env tags=”@Smoke and @regression” 

Test Execution Results 

Cypress Cucumber Framework result

After execution, you’ll see a summary with details like total tests, passed, failed, and skipped. This makes it easy to analyze the run and debug issues efficiently. 

By leveraging tags and custom scripts, Cypress lets us streamline test execution and manage complex scenarios with ease! 

Conclusion

The Cypress Cucumber Framework is a powerful combination that brings together the efficiency of Cypress and the collaboration-driven approach of Cucumber’s Behavior-Driven Development (BDD). By leveraging this framework, teams can write tests in plain language, improving communication and collaboration between technical and non-technical stakeholders. 

This approach ensures enhanced test readability, maintainability, and scalability through features like reusable step definitions, documentation, and integration with CI/CD pipelines. Additionally, its ability to manage complex scenarios using tags and a well-organized project structure makes it an excellent choice for modern automated testing. Adopting this framework enables faster feedback loops, higher test coverage, and user-focused application development. 

https://github.com/spurqlabs/Javascript-Cypress-BDD

Click here to read more blog like this.

0