Cypress - preserve cookies between tests

Cypress - preserve cookies between tests

  • cypress
  • testing
published 2020-03-12

This is in the Cypress docs, still it's something that can be said more than once.

When writing multiple tests, Cypress automatically clears all cookies by default to ensure a clean test state.

Although this is a good default behavior, it can be something you scratch your head on for a second or two, so - here's a quick example of what doesn't work and how to fix it:

context('Foo', () => {
  describe('something', () => {
    it('sets a cookie', () => {
      cy.setCookie('cookieA', 'a');
    })
 
    it('gets a cookie', () => {
      cy.getCookie('cookieA').should('have.property', 'value', 'a') // <- won't work
    })
  })

cookieA is set in the first test but cleared in the context of the second test, unless you specifically tell Cypress to back off:

context('Foo', () => {
 
  beforeEach(function () {
    Cypress.Cookies.preserveOnce('cookieA');
  })
  ...

There's also an option that lets you preserve cookies by whitelisting them.

When in doubt, read the docs.