0
0
Cypresstesting~15 mins

Cypress.Commands.add() - Build an Automation Script

Choose your learning style9 modes available
Create and use a custom Cypress command to login
Preconditions (2)
Step 1: Open the login page at '/login'
Step 2: Use the custom command 'login' with username 'testuser' and password 'Test@1234'
Step 3: Verify that the URL changes to '/dashboard' after login
Step 4: Verify that the page contains a welcome message with text 'Welcome, testuser!'
✅ Expected Result: User is successfully logged in using the custom command, redirected to '/dashboard', and sees the welcome message
Automation Requirements - Cypress
Assertions Needed:
URL should be '/dashboard' after login
Page should contain text 'Welcome, testuser!'
Best Practices:
Define custom commands in cypress/support/commands.js
Use Cypress.Commands.add() to create reusable commands
Use cy.visit() and cy.get() with proper selectors
Use assertions with cy.url().should() and cy.contains().should()
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
/// <reference types="cypress" />

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

// cypress/e2e/login_spec.js
describe('Login using custom command', () => {
  it('should login successfully and show welcome message', () => {
    cy.login('testuser', 'Test@1234');
    cy.url().should('include', '/dashboard');
    cy.contains('Welcome, testuser!').should('be.visible');
  });
});

The Cypress.Commands.add() function is used to create a custom command named login. This command visits the login page, fills in the username and password fields, and clicks the submit button.

In the test file, we call cy.login('testuser', 'Test@1234') to perform the login steps. Then, we assert that the URL includes /dashboard to confirm navigation after login. Finally, we check that the welcome message with the username is visible on the page.

This approach keeps the test clean and reusable by encapsulating login steps in a custom command.

Common Mistakes - 3 Pitfalls
Defining the custom command inside the test file instead of support/commands.js
Using hardcoded waits like cy.wait(5000) after clicking login
{'mistake': "Using incorrect selectors like cy.get('#username') when the input has name attribute", 'why_bad': 'Selectors may not match the actual elements, causing tests to fail.', 'correct_approach': 'Use accurate and stable selectors such as input[name="username"] or data-cy attributes.'}
Bonus Challenge

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

Show Hint