/// <reference types="cypress" />
// cypress/support/commands.js
Cypress.Commands.add('login', (email, password) => {
cy.visit('/login');
cy.get('#email').clear().type(email);
cy.get('#password').clear().type(password);
cy.get('#loginBtn').click();
cy.url().should('include', '/dashboard');
cy.get('#welcomeMsg').should('be.visible');
});
// cypress/e2e/login_spec.cy.js
describe('Login Handling Speeds Up Test Suites', () => {
beforeEach(() => {
cy.login('testuser@example.com', 'Password123!');
});
it('should show dashboard after login', () => {
cy.url().should('include', '/dashboard');
cy.get('#welcomeMsg').should('contain.text', 'Welcome');
});
it('should allow access to protected page without UI login again', () => {
cy.visit('/protected-page');
cy.url().should('include', '/protected-page');
cy.get('h1').should('contain.text', 'Protected Content');
});
});This solution uses Cypress to automate login handling.
First, a custom command cy.login is created in commands.js. It visits the login page, fills in email and password fields, clicks login, and asserts the URL and welcome message to confirm success.
Then, in the test file, beforeEach calls cy.login to perform login once before each test. This avoids repeating UI login steps in every test, speeding up the suite.
The tests verify the dashboard URL and welcome message, and also check access to a protected page without logging in again.
Using a custom command and assertions ensures code reuse, readability, and reliable verification of login success.