:::: MENU ::::

Software testing enthusiast.

This article is a part of the Cypress Test series. To read another story in this series, please follow the links below:

Cypress Test Series:

In this article, I will show you how to create custom commands in Cypress.
Cypress Custom Commands
Cypress Custom Commands

What are Custom Commands in Cypress?

Cypress custom commands are commands that are described by the user and used to create repeating steps in an automation test. By using custom commands you only need to define the command once and only use one line to call those commands.


The syntax for the custom commands in Cypress is as follows:
Cypress.Commands.add(function-name, func)

Cypress.Commands.add(function-name, options, func)

Cypress.Commands.overwrite(function-name, func)

  • function-name is the name of the command you are about to invoke.

  • func is a function that accepts the arguments passed to the command.

  • opts is an optional parameter used to describe the implicit characteristics of a custom command.

How to implement custom commands in Cypress?

For this article’s simulation, I will use a dummy test automation website from zero.webappsecurity.com.

This site is not a real banking site and any similarities to third-party products and/or Web sites are purely coincidental. To access the website, you can click the link below.


Suppose our application has a scenario where we need to log in to a website before we can do the real test within the user page. In doing so, we need to clear cookies and local storage. Then insert the username and password into the user_login and user_password fields. After that click remember_me and Sign in button

So, instead of invoking the get() and click() commands before every test scenario, we can add a new custom command which will execute the login procedure every time it is called. So, to achieve the result, we can declare a new custom command as follows. The script below is the implementation of a custom command in commands.js
Cypress.Commands.add(‘login’, (username, password) => {
cy.contains(‘Sign in’).click()

And, now it’s time to invoke the command:
describe(‘Login with Custom Command’, ()=>{
it(‘should execute custom command’, () => {
cy.login(‘username’, ‘password’)

So, it will call the login command and pass the parameter ‘username’ and ‘password’. Both parameters will be used as input values for the user_login and user_password fields. This way, we can execute login only using one line rather than typing every step in the login procedure.

Run the Cypress, and you will get the result as follows:
Result of custom command execution in Cypress

Custom command result

You can see in the log that the commands in the custom command are being executed.


Post a Comment

Find this blog interesting? Follow us