A simple way to create Re-Useable Commands in cypress

In this post, we will cover how to create Re-Useable Commands in cypress

Custom commands in cypress is nothing but creating our own customized function which can be used utilized in all parts of the cypress project with help of a single statement calling the function.

Custom commands work well when we’re needing to describe behavior that’s desirable across all of your tests. These are specific to your application and can be used everywhere.

To create Re-Useable commands In Cypress, we must go to folder cypress/support/commands.

Learn more about commands here

Type in the custom command within the template as shown below

Cypress.Commands.add('anyname', () => {
  //Your code here
    })
})

Suppose, if we want to create Re-Useable commands In cypress for logging into an application that is utilized for all test cases. Create a custom command as shown below.

create Re-Useable Commands

We can call the login command as same as the cypress command with syntax cy.

create Re-Useable Commands
Image shows the implementation of login custom command in test case which is created newly.

Below shows Custom command login is executed successfully, and this command can be utilized in all other test cases which have stepss for logging into the application.

create Re-Useable Commands

When the custom command is used along with the POM model it offers more reusability of the framework created for build scripts. Read more on POM model creation here.

Leave a Reply