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