0
0
Cypresstesting~5 mins

Why custom commands reduce duplication in Cypress

Choose your learning style9 modes available
Introduction

Custom commands help you write less repeated code. They make tests easier to read and maintain.

When you perform the same steps in many tests, like logging in.
When you want to simplify complex actions into one command.
When you want to keep your test code clean and easy to update.
When you need to share common actions across different test files.
Syntax
Cypress
Cypress.Commands.add('commandName', (param1, param2) => {
  // your code here
});

Use Cypress.Commands.add to create a custom command.

Give your command a clear name and pass any needed parameters.

Examples
This command logs in a user by typing email and password, then clicking 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 command clicks on a product by its name.
Cypress
Cypress.Commands.add('selectProduct', (productName) => {
  cy.contains(productName).click();
});
Sample Program

This test uses the custom login command to avoid repeating the login steps. It visits the login page, logs in, and checks the dashboard URL.

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

describe('User Login Test', () => {
  it('logs in successfully', () => {
    cy.visit('/login');
    cy.login('user@example.com', 'password123');
    cy.url().should('include', '/dashboard');
  });
});
OutputSuccess
Important Notes

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

If you change the login process, update the command once, not every test.

Use descriptive names so commands are easy to understand.

Summary

Custom commands reduce repeated code in tests.

They make tests easier to read and maintain.

Use them for common actions like login or navigation.