0
0
CypressHow-ToBeginner ยท 4 min read

How to Use Cypress.Commands.add for Custom Commands

Use Cypress.Commands.add to create custom reusable commands in Cypress tests by giving a command name and a callback function. This helps simplify test code by encapsulating repeated actions into one command.
๐Ÿ“

Syntax

The Cypress.Commands.add method takes two main parts: a command name as a string, and a callback function that defines what the command does. You can also pass arguments to the callback to customize the command.

javascript
Cypress.Commands.add('commandName', (arg1, arg2) => {
  // command implementation
});
๐Ÿ’ป

Example

This example shows how to create a custom command login that fills in username and password fields and clicks the login button. It demonstrates how to reuse this command in tests to keep code clean.

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 login redirects to /dashboard after filling credentials and clicking login.
โš ๏ธ

Common Pitfalls

  • Forgetting to add the custom command file to cypress/support/e2e.js or cypress/support/index.js so Cypress loads it.
  • Using arrow functions for test callbacks instead of regular functions, which breaks this context in Cypress.
  • Not returning Cypress commands inside the custom command, which can cause timing issues.
javascript
/* Wrong: arrow function loses context and no return */
Cypress.Commands.add('wrongCommand', () => {
  return cy.get('#element').click();
});

/* Right: use regular function and return chain */
Cypress.Commands.add('rightCommand', function() {
  return cy.get('#element').click();
});
๐Ÿ“Š

Quick Reference

Remember these tips when using Cypress.Commands.add:

  • Always name commands clearly.
  • Return Cypress commands to maintain chaining.
  • Load custom commands in cypress/support files.
  • Use regular functions if you need this context.
โœ…

Key Takeaways

Use Cypress.Commands.add to create reusable custom commands with a name and callback.
Return Cypress commands inside your custom command to keep proper chaining and timing.
Load your custom commands in Cypress support files to make them available in tests.
Avoid arrow functions in commands if you need access to Cypress's this context.
Custom commands simplify tests by encapsulating repeated actions into one call.