QA Automation Labs

How to Execute Tests with Cypress and Cucumber

image-15-768x349

How to Execute Tests with Cypress and Cucumber

Problem Statement

After Cypress Version 10 some changes are required to implement Cucumber in Cypress.

In this blog, I am covering those changes and will tell you what are the dependencies that need to update. Latest version of Cypress is 12.13.0

About Cypress And Cucumber

Cypress is a JavaScript-based end-to-end testing framework that allows you to write and run tests in a browser environment. It provides a comprehensive set of APIs and utilities for interacting with web applications and running assertions on their behavior.

Cucumber, on the other hand, is a tool that supports behavior-driven development (BDD) practices. It allows you to write test scenarios in a human-readable format using the Gherkin syntax. These scenarios describe the desired behavior of your application from a user’s perspective.

By combining Cypress and Cucumber, you can leverage the power of both tools. Cucumber provides a structured approach to defining test scenarios in a natural language format, while Cypress provides the capabilities to automate and execute those scenarios in a browser environment.

The integration between Cypress and Cucumber is achieved using a preprocessor, which translates the Gherkin syntax into executable Cypress code. This allows you to write your tests in a BDD-style using Cucumber, and then execute them using the Cypress test runner.

What is BDD?

Behavior-Driven Development (BDD) is a development approach that promotes communication between team members. This collaborative approach brings together the business and technical aspects of projects. BDD simulates how an application should behave from the end user’s perspective. The main goal of implementing BDD testing is to improve collaboration between developers, QA, DevOps, PO, BA, and other stakeholders.

BDD enables teams to communicate requirements better, detect problems early, and easily maintain software over time. The first is to make sure the entire team understands the requirements. Then teams can focus on preventing potential problems rather than fighting fires if they are found later. BDD ensures that everyone is in the loop from the beginning and throughout the process, which helps effective and quality communication between team members.

The below diagram gives us a summary of the steps involved in the BDD workflow.

BDD frameworks in the market

Some of the available BDD frameworks in the market are Cucumber, Quantum, SpecFlow, JBehave, Codeception, and others.

  • Cucumber is one of the market’s foremost well-liked BDD testing frameworks. Cucumber supports a variety of different programming languages, including Java and JavaScript.
  • Quantum is a Java-based open-source BDD testing framework designed by Perfecto.
  • SpecFlow is the most in-demand .NET BDD framework developed by TechTalk.
  • JBehave is a foremost Java-based BDD framework and other JVM languages, such as Groovy, Kotlin, and Scala.
  • Codeception is a famous PHP framework inspired by BDD. Codeception is a full-stack testing framework that achieves unit testing , API testing, and functional testing in addition to BDD testing.

What is Cucumber?

Cucumber is an open-source framework that supports BDD. Cucumber supports the Gherkin language, and in Gherkin, we can write our use cases in plain English that the tool reads easily. Cucumber reads the test written in Gherkin and verifies that the code works as it should. It does this by working on Gherkin scenarios and steps. Once all test cases are executed, a Cucumber report is generated with each step and scenario with pass and fail results.

What is Gherkin?

Gherkin is a language that developers use to write tests in Cucumber. Since Gherkin uses plain English, it’s meant to define use cases for a software system so that almost anyone can read and understand the use cases. The syntax of Gherkin promotes behavior-driven development because it allows developers, managers, business analysts, and other stakeholders to understand the project’s requirements and the life cycle.

Use of Gherkin language in writing the story by POs, BA’s makes stories more focused and easy to understand for the technical and non-technical side. Also, it becomes very easy for QA people to write their automation script because now requirements are more clear compared to when we are not using Cucumber with Gherkin syntax.

Gherkin uses easy English-like language that you could use to define the requirement and acceptance criteria. The most important basic format is as follows.

So, how does it work? First, you have to explain the feature that we want to implement, usually in the classic form of a user story: As a <person>, I Want <feature>, For <Business Value>.

Then you can define one or more business scenarios, meaning the overall behavior you want to receive with the user story.

Example:

Feature: Payments with Master Card.

As a Master Cardholder,

I Want to use my Master Card,

For paying my online bill.

Scenario: The Master Cardholder uses the Master card for online payment.

Given I am a Master Card Holder.

When I make online payments with my Master Card.

Then My master card is accepted

Gherkin Syntax

Next, let’s take a look at some of the steps in the Gherkin tests. These are Given, When, Then, And, or But.

Given

The objective of the Given steps is to get the system to a known state before the user (or an external system) starts interacting with the system (in the When steps).

Suppose we have to login into a site https://www.saucedemo.com/ So before login, we have to open the login screen so the user can login into the system. So we have to bring the system into the state where he can start interacting with the system (in the When steps).

Some examples of Given:

Example 1:

Given I am on the https://qaautomationlabs.com/

Example 2:

Another example may be supposed we want to create records into the database or set up the database, so in the Given statement, we can give the below detail.

Given Given there are no users on-site.

Given Given the database is clean.

When

When steps are action steps. The purpose of the When steps is to describe the key action the user performs. It’s suggested that you only have one When step for each scenario.

Let’s take the example of the https://www.saucedemo.com/ site.

Given I am on the “login page of saucedemo”

When I enter “the username” with “[email protected]

When I enter the “password” with “123456”

When I press “login”

Then

Then steps are the outcome steps. Then syntax can only be used in conjunction with the When syntax. In the Then section, we can describe what you want the system to do so that it can be compared to how the software works in practice.

Let’s take the example of the https://www.saucedemo.com/.

Given I am on the “login page of saucedemo

When I enter “the username” with “[email protected]

When I enter the “password” with “123456”

When I press “login”

Then user should be logged into the application

And, But

If you have several Given, When or Then steps then in that case you can use And, But. This helps keep your documentation managed and readable.

Example 1:

Scenario: Multiple Givens

Given one thing

Given another thing

Given yet another thing

When I open my eyes

Then I see something

Then I don’t see something else

We can add And, But in above example

Scenario: Multiple Givens

Given one thing

And another thing

And yet another thing

When I open my eyes

Then I see something

But I don’t see something else

Example 2:

Let’s take the example of the saucedemo

Given I am on the “login page of saucedemo

When I enter “the username” with “[email protected]

When I enter the “password” with “123456”

When I press “login”

Then the user should be logged into the application

We can add And, But in above example

Given I am on the “login page of saucedemo

When I enter “the username” with “[email protected]

And I enter the “password” with “123456”

And I press “login”

Then the user should be logged into the application

Background

Background allows you to add even more context to the scenarios in a feature. The Background is run before each of your scenarios. There can only be one background step for each feature.

Feature: Search and Edit Article

Background:

Given the user in the login page

When I enter “the username” with “Admin”

And I enter the “password” with “123456”

And I press “login”

Then the user should be logged into the application

Scenario: Search the blog

When I search blog “Cypress “

Then I should see “Cypress text in searched results”

Scenario: Edit the blog

When I edit the existing Post

And Click on Submit button

Then I should see “Your article was published”

Scenario Outline

The script outline runs once for each line of the example section except the header line. The steps of a scenario outline provide a template never executed directly. The scenario overview runs once for each row in the Examples section below (not counting the first row of the column headers).

Scenario Outline: Login into the Application

Given I am on the “login page of https://www.saucedemo.com/

When I enter <username>

And enter <password>

Then the user should be logged into the application

Examples:

| username | password |

[email protected] | ba@8838 |

[email protected] | b3a@8$3 |

[email protected] | xSba@3e3 |

Table

Tables are used for specifying a larger data set — usually as input to a Given or as expected output from a Then.

Examples:

| username | password |

[email protected] | ba@8838 |

[email protected] | b3a@8$3 |

[email protected] | xSba@3e3 |

First Step for Cucumber implementation is to install Cypress.

Lets Install Cypress …….

Installing Cypress

Step 1:

Create a folder and Generate package.json

  • Create a project, here naming it as Cypress10_With_Cucumber
  • Use the npm init command to create a package.json file

Step 2:

Install Cypress

To install Cypress, still, in the project folder, run > npm install cypress — save-dev

Once installed, Cypress version 10.9.0 is reflected as seen below

Installing Cucumber

We have to install two dev dependencies for Cucumber to run the test case in Cypress 10

Step 1:

Install the @badeball/cypress-cucumber-preprocessor using the command npm install -D @badeball/cypress-cucumber-preprocessor

Step 2:

Next, install one more dependencies ‘@bahmutov/cypress-esbuild-preprocessor’ using the commands npm install -D @bahmutov/cypress-esbuild-preprocessor.

We Can see both above dependencies are installed

Step 3:

Add below lines in cypress.config.js for cucumber preprocessor

const { defineConfig } = require(“cypress”);
const createBundler = require(“@bahmutov/cypress-esbuild-preprocessor”);
const addCucumberPreprocessorPlugin =
require(“@badeball/cypress-cucumber-preprocessor”).addCucumberPreprocessorPlugin;
const createEsbuildPlugin =
require(“@badeball/cypress-cucumber-preprocessor/esbuild”).createEsbuildPlugin;
module.exports = defineConfig({
e2e: {
async setupNodeEvents(on, config) {
const bundler = createBundler({
plugins: [createEsbuildPlugin(config)],
});

on(“file:preprocessor”, bundler);
await addCucumberPreprocessorPlugin(on, config);

return config;
},
specPattern: “cypress/e2e/**/*.feature”,
},
});

Covering the below scenarios in this blog

For demo purposes, I have taken the example of the site
http://qaautomationlabs.com/

Scenario Covered :

Scenario 1
Open the Url http://qaautomationlabs.com/
Verify Menu in Home Page
Validate the Title after login

Scenario 2
Open the Url http://qaautomationlabs.com/
Search the blog
Verify the correct blog name searched

Create Feature file

HomeTest.feature

Create a HomeTest feature file that covers verification of Menus in the site https://qaautomationlabs.com/ also verify the title of the site

Feature: Home Page

Background:
Given I navigate to the Website
Scenario: I want to verify content in Home Page
Then Validate the menus in home page

| menu_name |
| Home |
| Blogs |
| Contact Us |
Scenario: I want to validate title of home page
Then Validate the title after login
| title |
| About Us — QAAutomationLabs |

SearchProductTest.feature

Create a SearchProductTest feature file which covers searching the blog and verifies the searched text “Cypress” in the search result

Feature: Search Product

Background:
Given I navigate to the Website

Scenario: I want to search the product in home page
Then Search the blog
| blog |
| Cypress |
Then Verify correct blog name searched
| searchValue |
| Cypress |

Folder structure looks like the attached below

Create Cypress Test cases

Create TestClass

Create HomeTest.spec.js under Tests ->HomeTest

/// <reference types=”cypress” />
import { Given, Then } from “@badeball/cypress-cucumber-preprocessor”;
import homePage from “../../Pages/HomePage/HomePage.spec”;
beforeEach(() => {
cy.viewport(1600, 720);
});
Given(“I navigate to the Website”, () => {
homePage.enterURL();
});
Then(“Validate the menus in home page”, (datatable) => {
datatable.hashes().forEach((element) => {
homePage.validateMenus(element.menu_name);
});
});
Then(“Validate the title after login”, (datatable) => {
datatable.hashes().forEach((element) => {
homePage.verifyPageTitle(element.title);
});
});

Create SearchProductTest.spec.js under Tests ->SearchProductTest

/// <reference types=”cypress” />
import { Given, When, Then } from “@badeball/cypress-cucumber-preprocessor”;
import searchProduct from “../../Pages//SearchProductPage/SearchProductPage.spec”;
import homePage from “../../Pages/HomePage/HomePage.spec”;

Given(“I navigate to the Website”, () => {
homePage.enterURL();
});
When(“Search the blog”, (datatable) => {
datatable.hashes().forEach((element) => {
searchProduct.SearchProduct(element.blog);
});
});
Then(“Verify correct blog name searched”, (datatable) => {
datatable.hashes().forEach((element) => {
searchProduct.verifyProduct(element.searchValue);
});
});

Create PageClass

HomePage.spec.js under Pages ->HomePage Folder

/// <reference types =”cypress”/>

class HomePage {
enterURL() {
cy.visit(“https://qaautomationlabs.com/“);
}
validateMenus(menus) {
cy.contains(menus);
return this;
}
verifyPageTitle() {
return cy.title().should(“eq”, “About Us — QAAutomationLabs”);
}
}
const homepage = new HomePage();
export default homepage;

SearchProductPage.spec.js under Pages ->SearchProductPage Folder

class SearchProduct {
SearchProduct(searchProductName) {
cy.get(“#top-nav > .page-item-5 > a > span”).click({ force: true });
cy.get(“[id=’wp-block-search__input-2′]”)
.click({ force: true })
.type(searchProductName);
cy.get(“[id=’search-icon’]”).click({ force: true });
}
verifyProduct(searchProductName) {
cy.get(“[id=’main’]”).contains(searchProductName);
}
}
const searchProduct = new SearchProduct();
export default searchProduct;

Run Test cases

Run the command: yarn run cypress open.In the below screenshot here we can see two feature files are displaying

Run HomeTest.feature

In below screenshot we can see menus in the Home page and the title of the site is verified

Run SearchProductTest.feature

In the below screenshot we can see the site is open, search the text “Cypress” and verify the search text in the search results

Leave a Comment

Your email address will not be published. Required fields are marked *

Recent Posts

AI-Driven Testing with Applitools Autonomous

The demand for high quality software in the fast paced tech environment has never been greater. Since companies spend more on QA to make sure their pr
Read More

Visual Regression Testing Using Playwright

“Have you ever thought, ‘Why wasn’t that noticed?’ or ‘Is the bug so obvious that it should have been caught right away?
Read More

Cypress vs Selenium: Choosing the Best Tool for Your Automation Needs

Choosing the right testing tool for your project can be a challenging task. Two of the most widely used options are Cypress and Selenium, and understa
Read More