0
0
CypressConceptBeginner · 3 min read

What Is Custom Command in Cypress: Simple Explanation and Example

A custom command in Cypress is a user-defined function that extends Cypress's built-in commands to simplify repetitive tasks. It helps you write cleaner and reusable test code by creating your own commands with Cypress.Commands.add().
⚙️

How It Works

Think of a custom command in Cypress like creating your own shortcut for a task you do often. Instead of writing the same steps again and again, you bundle them into one command with a name you choose. This is similar to making a recipe for your favorite dish so you can cook it anytime without remembering every step.

Under the hood, Cypress lets you add these commands using Cypress.Commands.add(). Once added, you can call your custom command just like any built-in Cypress command. This keeps your test scripts neat and easier to read, especially when tests get bigger.

💻

Example

This example shows how to create a custom command to log in a user by filling username and password fields and clicking the login button.

javascript
Cypress.Commands.add('login', (username, password) => {
  cy.get('#username').type(username);
  cy.get('#password').type(password);
  cy.get('#login-button').click();
});

// Usage in a test
describe('Login Test', () => {
  it('logs in with valid credentials', () => {
    cy.visit('/login');
    cy.login('user1', 'pass123');
    cy.url().should('include', '/dashboard');
  });
});
Output
Test passes if the user is redirected to /dashboard after login.
🎯

When to Use

Use custom commands when you have repeated actions in your tests, like logging in, filling forms, or navigating menus. They save time and reduce mistakes by reusing tested code. For example, if many tests require logging in, a custom command makes your tests shorter and easier to maintain.

They also help when you want to hide complex steps behind a simple command name, making your test scripts more readable for others or your future self.

Key Points

  • Custom commands extend Cypress with your own reusable functions.
  • They are created using Cypress.Commands.add().
  • They help keep tests clean and DRY (Don't Repeat Yourself).
  • Useful for repeated or complex actions like login or form filling.
  • Make test code easier to read and maintain.

Key Takeaways

Custom commands let you create reusable test steps to simplify your Cypress tests.
Define custom commands with Cypress.Commands.add() and call them like built-in commands.
Use them to avoid repeating code and make tests easier to read and maintain.
Ideal for common actions like logging in or filling forms across many tests.