cy.session() for session caching in Cypress - Build an Automation Script
describe('Login with session caching using cy.session()', () => { const username = 'testuser'; const password = 'Test@1234'; function login() { cy.visit('/login'); cy.get('#username').type(username); cy.get('#password').type(password); cy.get('#loginBtn').click(); cy.url().should('include', '/dashboard'); } beforeEach(() => { cy.session('user-session', login); }); it('should login and cache session', () => { // Session is created in beforeEach cy.visit('/dashboard'); cy.url().should('include', '/dashboard'); cy.get('#logoutBtn').should('be.visible'); }); it('should logout and require login again', () => { cy.visit('/dashboard'); cy.get('#logoutBtn').click(); cy.url().should('include', '/login'); // After logout, session should be cleared cy.session('user-session', login, { cacheAcrossSpecs: false }); }); });
The test suite uses cy.session() to cache the login session under the name 'user-session'.
The login function performs the login steps: visiting the login page, entering credentials, clicking login, and verifying the dashboard URL.
In beforeEach, cy.session() runs the login function only if the session is not cached, speeding up tests by reusing the session.
The first test verifies that after session caching, visiting '/dashboard' shows the dashboard page and logout button.
The second test logs out by clicking the logout button, verifies the URL returns to '/login', and clears the session cache to ensure login is required again.
Selectors use stable IDs, and assertions check URL and element visibility to confirm correct behavior.
Now add data-driven testing with 3 different sets of valid user credentials using cy.session()