Test Overview
This test demonstrates how to preserve the login state between multiple tests in Cypress by using cookies. It verifies that the user remains logged in across tests without needing to log in again.
This test demonstrates how to preserve the login state between multiple tests in Cypress by using cookies. It verifies that the user remains logged in across tests without needing to log in again.
describe('Preserve login state between tests', () => { before(() => { cy.visit('https://example.com/login'); cy.get('#username').type('testuser'); cy.get('#password').type('password123'); cy.get('#login-button').click(); cy.url().should('include', '/dashboard'); }); beforeEach(() => { Cypress.Cookies.preserveOnce('session_id', 'auth_token'); }); it('should display user dashboard', () => { cy.get('h1').should('contain', 'Dashboard'); }); it('should access profile page without logging in again', () => { cy.visit('https://example.com/profile'); cy.get('h2').should('contain', 'User Profile'); }); });
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test suite starts; before hook runs | Browser opens at login page https://example.com/login | - | PASS |
| 2 | Find username input and type 'testuser' | Username field filled with 'testuser' | - | PASS |
| 3 | Find password input and type 'password123' | Password field filled | - | PASS |
| 4 | Click login button | Login form submitted | - | PASS |
| 5 | Verify URL includes '/dashboard' after login | User redirected to dashboard page | URL contains '/dashboard' | PASS |
| 6 | beforeEach hook runs; preserve cookies 'session_id' and 'auth_token' | Cookies preserved for next tests | - | PASS |
| 7 | Test 1: Check dashboard heading text | Dashboard page visible | Heading contains text 'Dashboard' | PASS |
| 8 | beforeEach hook runs again; preserve cookies | Cookies preserved again for next test | - | PASS |
| 9 | Test 2: Visit profile page https://example.com/profile | Profile page loaded | - | PASS |
| 10 | Verify profile page heading text | Profile page heading visible | Heading contains text 'User Profile' | PASS |