Understanding Reusable Custom Commands in Cypress Automation

Sahithi Gundu
2 min readDec 31, 2021

Cypress has its own Support file named commands.js, where we can define and create the reusable custom commands.

A great place to define or overwrite commands is in your cypress/support/commands.js file, since it is loaded before any test files are evaluated via an import statement in your support file .
— — — — — — — — — — — — — — —

How are Custom Commands used in Cypress ?

Custom Commands are used to create Reusable methods in cypress automation.

Example: Let Say, we have to create a Test Suite for an eCommerce Website where you need to Login as Customer ,
1. Search for multiple products
2. Add them to Cart.

In this case, customer searches for products and Adds them to cart multiple times. i.e; Above (1) & (2) steps need to be executed multiple times in cypress. In such scenarios Reusable methods can be used. We can create custom commands so that we can reuse the same scripts multiple times.

Add your Custom Commands in cypress/support/commands.js file.

Cypress.Commands.add('Search_and_Add_to_Cart', (Productname) => {cy.get('input.search-field')
.click()
.type(Productname) //here we are mentioning the variable
cy.get('div.select-any-product-from-search-results')
.click()
cy.get('button.add-to-cart')
.click()
cy.get('div.title-name')
.should('contain',Productname) //Verify the product is added
})

Our custom command is created in Commands.js file. Now this is how we reuse this command in our Main scripts in cypress/integration/scripts/ecommerce.spec.js file..

/// <reference types="Cypress" />describe('ECommerce Workflow using Cypress', () => {
it('Login, Search, AddtoCart', () => {
cy.visit('www.ecommerse.com') cy.get('h2-title')
.should('contain','Welcome Sahithi')
//Calling the reusable method with its Name cy.Search_and_Add_to_Cart('Cypress ebook by Mihira') cy.Search_and_Add_to_Cart('Ninu Coffee Makers') cy.Search_and_Add_to_Cart('Nichu Cookies') })
})

Reference: https://docs.cypress.io/api/cypress-api/custom-commands#Syntax

Hope this is helpful :)

Best Regards,
Sahithi Gundu,
gsahithi.cse@gmail.com

Cypress version 9.0.0 Dt. 31–12–2021

--

--