Automate login using custom command to reduce duplication
Preconditions (1)
✅ Expected Result: Both login attempts succeed and user is redirected to '/dashboard' without duplicating login steps in test code
/// <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.
Now add data-driven testing with 3 different username and password pairs using the custom login command
Cypress.Commands.add('login', (user) => { cy.get('#username').type(user.name); cy.get('#password').type(user.pass); cy.get('#submit').click(); }); cy.login({name: 'alice', pass: '1234'}); cy.url().should('include', '/dashboard'); Cypress.Commands.add('clickButton', () => { cy.get('button.submit').click(); }); fillForm that fills multiple fields on a page. Which approach best reduces duplication and improves test readability?cy.get().type() lines in every test needing the form filled.) causes duplication and harder maintenance.fillForm to accept an object with field names and values, then fill each field inside the command.) centralizes logic and improves readability.cy.exec() to run external scripts that fill the form.) is not for UI actions.Pass the test and this pattern moves unknown