0
0
Cypresstesting~5 mins

Cypress.Commands.add()

Choose your learning style9 modes available
Introduction

Cypress.Commands.add() lets you create your own custom commands to reuse steps easily in tests.

You want to click a button that appears on many pages.
You need to fill a login form in many tests.
You want to check a common element's text multiple times.
You want to simplify complex test steps into one command.
You want to keep your test code clean and easy to read.
Syntax
Cypress
Cypress.Commands.add('commandName', (arg1, arg2, ...) => {
  // your custom command code here
});

The first argument is the name of your new command as a string.

The second argument is a function that runs when you call the command.

Examples
This adds a 'login' command to fill email and password and click submit.
Cypress
Cypress.Commands.add('login', (email, password) => {
  cy.get('#email').type(email);
  cy.get('#password').type(password);
  cy.get('button[type=submit]').click();
});
This adds a 'clickButton' command to click a button by its label text.
Cypress
Cypress.Commands.add('clickButton', (label) => {
  cy.contains('button', label).click();
});
Sample Program

This test uses the custom 'login' command to enter credentials and check if the user reaches the dashboard page.

Cypress
Cypress.Commands.add('login', (email, password) => {
  cy.get('#email').type(email);
  cy.get('#password').type(password);
  cy.get('button[type=submit]').click();
});

describe('Login Test', () => {
  it('logs in with valid credentials', () => {
    cy.visit('https://example.com/login');
    cy.login('user@example.com', 'mypassword');
    cy.url().should('include', '/dashboard');
  });
});
OutputSuccess
Important Notes

Custom commands help keep tests DRY (Don't Repeat Yourself).

Always choose clear command names to make tests easy to read.

You can add commands for any repeated action in your tests.

Summary

Cypress.Commands.add() creates reusable custom commands.

Use it to simplify and clean your test code.

Call your custom commands like built-in Cypress commands.