0
0
Cypresstesting~3 mins

Why Cypress.Commands.add()? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write a test step once and use it everywhere without copying?

The Scenario

Imagine testing a website where you have to log in many times manually by typing the username and password each time in your test scripts.

You copy and paste the same steps over and over in every test.

The Problem

This manual way is slow and boring.

It's easy to make mistakes copying the same steps repeatedly.

If the login process changes, you must update every test, which wastes time and causes errors.

The Solution

Cypress.Commands.add() lets you create your own custom commands.

You write the login steps once, then reuse them everywhere by calling your new command.

This saves time, reduces mistakes, and makes tests easier to update.

Before vs After
Before
cy.get('#username').type('user')
cy.get('#password').type('pass')
cy.get('#login').click()
After
Cypress.Commands.add('login', () => {
  cy.get('#username').type('user')
  cy.get('#password').type('pass')
  cy.get('#login').click()
})

cy.login()
What It Enables

You can build a library of reusable commands that make your tests cleaner, faster, and easier to maintain.

Real Life Example

In a big project, you create a custom command for logging in once.

Every test just calls cy.login() instead of repeating the login steps.

When the login changes, you update only one place.

Key Takeaways

Manual repetition of test steps is slow and error-prone.

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

Custom commands make tests simpler and easier to maintain.