0
0
CypressHow-ToBeginner ยท 3 min read

How to Create Custom Command in Cypress for Reusable Tests

To create a custom command in Cypress, add your command code inside cypress/support/commands.js using Cypress.Commands.add(). This lets you reuse complex or repeated test steps by calling your custom command in tests with cy.yourCommandName().
๐Ÿ“

Syntax

Use Cypress.Commands.add() to define a custom command. It takes two arguments: the command name as a string, and a callback function with the command's actions.

  • Command Name: The name you will use to call the command in tests.
  • Callback Function: The code that runs when the command is called. It can accept parameters.
javascript
Cypress.Commands.add('commandName', (param1, param2) => {
  // command actions here
});
๐Ÿ’ป

Example

This example creates a custom command login that fills in username and password fields and clicks the login button. You can call cy.login('user', 'pass') in your tests to reuse this login step.

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

// Usage in a test
// describe('Login Test', () => {
//   it('logs in user', () => {
//     cy.visit('/login');
//     cy.login('myUser', 'myPass');
//     cy.url().should('include', '/dashboard');
//   });
// });
Output
Test passes if login succeeds and URL includes '/dashboard'.
โš ๏ธ

Common Pitfalls

Common mistakes when creating custom commands include:

  • Not importing commands.js in cypress/support/e2e.js, so commands are not registered.
  • Using incorrect selectors that break the command.
  • Not returning Cypress chainables when needed, which can break command chaining.
  • Overcomplicating commands instead of keeping them focused and reusable.
javascript
/* Wrong: Not returning chainable */
Cypress.Commands.add('wrongCommand', () => {
  cy.get('#element').click();
});

/* Right: Return chainable for chaining */
Cypress.Commands.add('rightCommand', () => {
  return cy.get('#element').click();
});
๐Ÿ“Š

Quick Reference

Summary tips for custom commands:

  • Define commands in cypress/support/commands.js.
  • Always import commands.js in cypress/support/e2e.js.
  • Use clear, descriptive command names.
  • Return Cypress chainables to support chaining.
  • Keep commands focused on one task for reusability.
โœ…

Key Takeaways

Create custom commands with Cypress.Commands.add() inside cypress/support/commands.js.
Always import your commands file in cypress/support/e2e.js to register commands.
Return Cypress chainables from commands to enable chaining in tests.
Use custom commands to simplify and reuse common test steps.
Keep commands simple and focused for easier maintenance.