Custom Commands for Reusable Test Logic
You'll learn how to create reusable Cypress commands that eliminate duplication and make your tests read like plain English.
When writing multiple Cypress tests, you'll often repeat the same sequences of actions—logging in, filling out forms, navigating to specific states. Instead of copying this code everywhere, Cypress lets you define custom commands that bundle these steps into simple, readable methods.
How Custom Commands Work
Think of custom commands as creating your own vocabulary for Cypress. Just like cy.get() and cy.click() are built-in words Cypress understands, you can teach it new words specific to your application.
You define custom commands in cypress/support/commands.js:
Cypress.Commands.add('login', (email, password) => {
cy.visit('/login');
cy.get('[data-testid="email-input"]').type(email);
cy.get('[data-testid="password-input"]').type(password);
cy.get('[data-testid="login-button"]').click();
cy.url().should('include', '/dashboard');
});
Now every test can simply use:
cy.login('user@example.com', 'password123');
Benefits in Practice
Custom commands transform verbose, duplicated test code into clear intent. Instead of eight lines of setup, you write one line that says exactly what you mean: "log in as this user."
You can also create commands for common assertions:
Cypress.Commands.add('shouldBeOnDashboard', () => {
cy.url().should('include', '/dashboard');
cy.contains('Welcome back').should('be.visible');
});
This keeps your tests focused on the unique logic being tested, not repetitive setup.
Key Takeaway: Custom commands in cypress/support/commands.js let you extract repeated test logic into reusable, readable methods that make your test suite easier to write and maintain.