0
0
Cypresstesting~10 mins

Preserving state between tests in Cypress - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - Cypress
Cypress
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');
  });
});
Execution Trace - 10 Steps
StepActionSystem StateAssertionResult
1Test suite starts; before hook runsBrowser opens at login page https://example.com/login-PASS
2Find username input and type 'testuser'Username field filled with 'testuser'-PASS
3Find password input and type 'password123'Password field filled-PASS
4Click login buttonLogin form submitted-PASS
5Verify URL includes '/dashboard' after loginUser redirected to dashboard pageURL contains '/dashboard'PASS
6beforeEach hook runs; preserve cookies 'session_id' and 'auth_token'Cookies preserved for next tests-PASS
7Test 1: Check dashboard heading textDashboard page visibleHeading contains text 'Dashboard'PASS
8beforeEach hook runs again; preserve cookiesCookies preserved again for next test-PASS
9Test 2: Visit profile page https://example.com/profileProfile page loaded-PASS
10Verify profile page heading textProfile page heading visibleHeading contains text 'User Profile'PASS
Failure Scenario
Failing Condition: Cookies 'session_id' and 'auth_token' are not preserved between tests
Execution Trace Quiz - 3 Questions
Test your understanding
Why is Cypress.Cookies.preserveOnce used in beforeEach?
ATo clear cookies before each test
BTo reload the page automatically
CTo keep login cookies so user stays logged in between tests
DTo reset the browser session
Key Result
Preserving cookies between tests in Cypress allows tests to share login state, avoiding repeated login steps and making tests faster and more reliable.