Preserving state between tests in Cypress - Build an Automation Script
describe('Preserve user login state between tests', () => { before(() => { // Log in once before all tests cy.visit('https://example.com/login'); cy.get('#username').type('testuser'); cy.get('#password').type('Test@1234'); cy.get('#loginBtn').click(); cy.url().should('eq', 'https://example.com/dashboard'); // Save cookies/local storage to preserve session cy.getCookies().then(cookies => { Cypress.Cookies.preserveOnce(...cookies.map(c => c.name)); }); }); beforeEach(() => { // Preserve cookies before each test to keep session Cypress.Cookies.preserveOnce('session_id', 'auth_token'); }); it('should show username on profile page', () => { cy.visit('https://example.com/profile'); cy.contains('testuser').should('be.visible'); }); it('should remain logged in after page reload', () => { cy.visit('https://example.com/profile'); cy.reload(); cy.contains('testuser').should('be.visible'); }); });
The before() hook logs in the user once before all tests run. It visits the login page, enters credentials, clicks login, and verifies the dashboard URL.
After login, it saves cookies to preserve the session. The beforeEach() hook preserves important cookies like session_id and auth_token before each test to keep the user logged in.
The first test visits the profile page and checks that the username testuser is visible, confirming the user is logged in.
The second test reloads the profile page and verifies the username is still visible, confirming the login state is preserved after reload.
This approach avoids logging in before every test and uses Cypress best practices for session preservation.
Now add data-driven testing with 3 different user accounts to verify login state preservation for each.