Writing Reusable Custom Commands in Cypress

 Cypress is a powerful JavaScript-based end-to-end testing framework widely used for testing modern web applications. One of its standout features is the ability to write custom commands—reusable wrappers around common or complex logic—which can help reduce duplication, improve readability, and enforce consistency across your test suite.

In this blog, we’ll explore how to write reusable custom commands in Cypress, why they matter, and how to structure them for maintainable, scalable testing.


What Are Custom Commands in Cypress?

Custom commands are user-defined functions that extend Cypress’s built-in cy object. They allow you to encapsulate frequently-used sequences of actions or assertions.

For example, if you find yourself logging into your application at the beginning of multiple test cases, you can write a custom command like cy.login() and reuse it wherever needed.


Benefits of Custom Commands

DRY (Don’t Repeat Yourself): Avoid duplicating test code across multiple spec files.

Improved Readability: Replace long code blocks with descriptive commands.

Centralized Maintenance: Update the logic in one place to affect all tests.

Better Abstraction: Focus on test intent rather than implementation details.


Creating Your First Custom Command

To create a custom command, you use the Cypress.Commands.add() method, typically in the cypress/support/commands.js file.


Example: A Login Command

javascript

Copy

Edit

// cypress/support/commands.js


Cypress.Commands.add('login', (email, password) => {

  cy.visit('/login');

  cy.get('input[name=email]').type(email);

  cy.get('input[name=password]').type(password);

  cy.get('button[type=submit]').click();

});

Usage in a Test

javascript

Copy

Edit

// cypress/e2e/login.spec.js


describe('User Login', () => {

  it('should log in successfully', () => {

    cy.login('user@example.com', 'securePassword123');

    cy.url().should('include', '/dashboard');

  });

});

Now, instead of repeating the login steps in every test, you simply call cy.login().


Passing Options and Handling Edge Cases

You can enhance your commands by passing optional parameters or adding conditional logic:


javascript

Copy

Edit

Cypress.Commands.add('login', ({ email = 'admin@test.com', password = 'admin123' } = {}) => {

  cy.visit('/login');

  cy.get('#email').type(email);

  cy.get('#password').type(password);

  cy.get('form').submit();

});

Then use it like:


javascript

Copy

Edit

cy.login(); // Uses default values

cy.login({ email: 'user@test.com', password: 'userpass' });

Creating Commands for API Requests

Custom commands aren’t limited to UI interactions. You can use them for API calls, test data creation, or cleanup tasks:


javascript

Copy

Edit

Cypress.Commands.add('createUser', (user) => {

  cy.request('POST', '/api/users', user);

});

This allows you to programmatically create test users before running UI tests.


Best Practices

Name commands descriptively: Use names like cy.loginAsAdmin(), cy.fillContactForm(), etc.

Avoid logic-heavy commands: Keep commands focused on single responsibilities.

Use TypeScript (optional): For type safety and IntelliSense support.

Test your commands: Validate that custom commands work independently.

Document them: Maintain documentation to help team members understand usage.


Conclusion

Writing reusable custom commands in Cypress helps streamline your test automation efforts, promotes clean and maintainable code, and enhances test readability. Whether you’re logging in, filling forms, or setting up API data, encapsulating that logic into commands reduces duplication and empowers your team to write faster, more efficient tests. As your test suite grows, well-structured custom commands become essential for maintaining quality and speed in your testing workflow.


Learn Cypress Training

Read More: Cypress vs Playwright: Which is Better?
Read More: Difference Between Cypress and Selenium
Read More: Interacting with DOM Elements in Cypress

Visit IHUB Talent Training Institute in Hyderabad
Get Direction

Comments

Popular posts from this blog

How to Use Tosca's Test Configuration Parameters

Using Hibernate ORM for Fullstack Java Data Management

Creating a Test Execution Report with Charts in Playwright