/// <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.