0
0
Cypresstesting~10 mins

Why custom commands reduce duplication in Cypress - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test demonstrates how using a custom Cypress command reduces code duplication by reusing a login process in multiple tests. It verifies that the user can successfully log in using the custom command.

Test Code - Cypress
Cypress
// cypress/support/commands.js
Cypress.Commands.add('login', (username, password) => {
  cy.get('#username').type(username)
  cy.get('#password').type(password)
  cy.get('#login-button').click()
})

// cypress/e2e/login_spec.cy.js
describe('Login Tests with Custom Command', () => {
  beforeEach(() => {
    cy.visit('/login')
  })

  it('logs in successfully using custom command', () => {
    cy.login('user1', 'pass123')
    cy.url().should('include', '/dashboard')
    cy.get('h1').should('contain', 'Welcome')
  })

  it('logs in another user using custom command', () => {
    cy.login('user2', 'pass456')
    cy.url().should('include', '/dashboard')
    cy.get('h1').should('contain', 'Welcome')
  })
})
Execution Trace - 9 Steps
StepActionSystem StateAssertionResult
1Test starts and browser opensBrowser is ready to run tests-PASS
2Navigates to /login pageLogin page is displayed with username, password fields and login buttonURL includes '/login'PASS
3Calls custom command cy.login('user1', 'pass123')Username and password fields are filled, login button is clicked-PASS
4Checks URL includes '/dashboard' after loginDashboard page is loadedURL contains '/dashboard'PASS
5Checks page header contains 'Welcome'Dashboard page shows welcome messageHeader text contains 'Welcome'PASS
6Starts second test, navigates to /login pageLogin page is displayed againURL includes '/login'PASS
7Calls custom command cy.login('user2', 'pass456')Username and password fields are filled with new user, login button clicked-PASS
8Checks URL includes '/dashboard' after second loginDashboard page is loaded for second userURL contains '/dashboard'PASS
9Checks page header contains 'Welcome' for second userDashboard page shows welcome messageHeader text contains 'Welcome'PASS
Failure Scenario
Failing Condition: If the custom command cy.login fails to find username or password fields or login button
Execution Trace Quiz - 3 Questions
Test your understanding
What is the main benefit of using the custom command cy.login in these tests?
AIt changes the URL automatically
BIt makes the test run faster by skipping login
CIt reduces code duplication by reusing login steps
DIt disables assertions in the test
Key Result
Using custom commands in Cypress helps keep tests clean and avoids repeating the same steps, making tests easier to maintain and read.