0
0
Cypresstesting~5 mins

Preserving state between tests in Cypress

Choose your learning style9 modes available
Introduction

Sometimes tests need to remember things like login info so you don't have to do the same steps again and again.

You want to stay logged in across multiple tests without logging in each time.
You need to keep cookies or local storage data between tests.
You want faster tests by skipping repeated setup steps.
You want to test a flow that spans multiple pages or actions.
You want to avoid flaky tests caused by resetting state too often.
Syntax
Cypress
Cypress.Cookies.preserveOnce('cookieName1', 'cookieName2')

// or

Cypress.Cookies.defaults({ preserve: ['cookieName'] })

Use preserveOnce inside a beforeEach hook to keep cookies for that test run only.

Use defaults to keep cookies for all tests automatically.

Examples
This keeps the 'session_id' and 'auth_token' cookies between tests so you stay logged in.
Cypress
beforeEach(() => {
  Cypress.Cookies.preserveOnce('session_id', 'auth_token')
})
This tells Cypress to always keep the 'session_id' cookie for all tests in the file.
Cypress
Cypress.Cookies.defaults({
  preserve: ['session_id']
})
Log in once before all tests, then keep the session cookie for each test.
Cypress
before(() => {
  cy.login() // custom command to log in once
})

beforeEach(() => {
  Cypress.Cookies.preserveOnce('session_id')
})
Sample Program

This test suite logs in once before all tests. Then it keeps the 'session_id' cookie between tests so the user stays logged in. Test 1 checks the dashboard greeting. Test 2 visits the profile page without logging in again.

Cypress
describe('Preserve login state between tests', () => {
  before(() => {
    cy.visit('/login')
    cy.get('#username').type('user1')
    cy.get('#password').type('password123')
    cy.get('button[type=submit]').click()
    cy.url().should('include', '/dashboard')
  })

  beforeEach(() => {
    Cypress.Cookies.preserveOnce('session_id')
  })

  it('Test 1: Check dashboard greeting', () => {
    cy.visit('/dashboard')
    cy.contains('Welcome, user1').should('be.visible')
  })

  it('Test 2: Visit profile page without logging in again', () => {
    cy.visit('/profile')
    cy.contains('user1').should('be.visible')
  })
})
OutputSuccess
Important Notes

Preserving cookies is the most common way to keep login state.

You can also preserve local storage or session storage using custom commands.

Be careful: preserving too much state can make tests depend on each other, which is not ideal.

Summary

Preserving state helps tests run faster and avoid repeating steps.

Use Cypress.Cookies.preserveOnce or Cypress.Cookies.defaults to keep cookies.

Keep tests independent by preserving only what is necessary.