0
0
Cypresstesting~15 mins

Why custom commands reduce duplication in Cypress - Automation Benefits in Action

Choose your learning style9 modes available
Automate login using custom command to reduce duplication
Preconditions (1)
Step 1: Use the custom command 'login' with username 'user1' and password 'Password1!'
Step 2: Verify the URL changes to '/dashboard'
Step 3: Use the custom command 'login' with username 'user2' and password 'Password2!'
Step 4: Verify the URL changes to '/dashboard'
✅ Expected Result: Both login attempts succeed and user is redirected to '/dashboard' without duplicating login steps in test code
Automation Requirements - Cypress
Assertions Needed:
Verify URL is '/dashboard' after login
Best Practices:
Create a custom command for login to reuse login steps
Use Cypress commands chaining and assertions
Avoid duplicating selectors and login steps in multiple tests
Automated Solution
Cypress
/// <reference types="cypress" />

// cypress/support/commands.js
Cypress.Commands.add('login', (username, password) => {
  cy.visit('/login');
  cy.get('#username').clear().type(username);
  cy.get('#password').clear().type(password);
  cy.get('button[type="submit"]').click();
});

// cypress/e2e/login_spec.cy.js
describe('Login Tests Using Custom Command', () => {
  it('logs in user1 successfully', () => {
    cy.login('user1', 'Password1!');
    cy.url().should('include', '/dashboard');
  });

  it('logs in user2 successfully', () => {
    cy.login('user2', 'Password2!');
    cy.url().should('include', '/dashboard');
  });
});

The login custom command is defined once in cypress/support/commands.js. It visits the login page, fills username and password fields, and clicks submit. This avoids repeating these steps in every test.

In the test file login_spec.cy.js, we call cy.login() with different credentials. After login, we assert the URL includes /dashboard to confirm success.

This approach reduces duplication by centralizing login steps. If the login process changes, only the custom command needs updating, not every test.

Common Mistakes - 3 Pitfalls
Writing login steps repeatedly in each test without using a custom command
Using hardcoded selectors inside tests instead of inside the custom command
Not clearing input fields before typing in the custom command
Bonus Challenge

Now add data-driven testing with 3 different username and password pairs using the custom login command

Show Hint