Sometimes tests need to remember things like login info so you don't have to do the same steps again and again.
Preserving state between tests in 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.
beforeEach(() => {
Cypress.Cookies.preserveOnce('session_id', 'auth_token')
})Cypress.Cookies.defaults({
preserve: ['session_id']
})before(() => {
cy.login() // custom command to log in once
})
beforeEach(() => {
Cypress.Cookies.preserveOnce('session_id')
})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.
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') }) })
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.
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.