Cypress Preserve Cookies

Profile picture for user arilio666

NOTE: Preserve Once in cypress is deprecated as of version 9.7.0, and instead, an experimental cypress session can be used to preserve/save cookies with experimental mode turned on.

In this article, however, we will cover what preserve once is and how it was used. Later cy.session() will be covered in a separate article for clear understanding.

  • Cypress allows you to preserve or save cookies for multiple tests by using the preserve cookies command.
  • This will make the test even faster by preloading each test with previously saved sessions.
  • Cypress typically clears every cookie before each new test and starts a clean slate.
  • This makes tests sluggish as they start new every time after the visit.
  • Preserving cookies and using that later on in other tests will make tests fast.

Syntax:

Cypress.Cookies.preserveOnce(names...)

Arguments:

Names: Name of the cookies to be preserved. An unlimited number of args can be passed.

Correct Use:

cy.cookies.preserveOnce()
describe('Dashboard', () => {
 beforeEach(() => {
   Cypress.Cookies.preserveOnce('session_id', 'remember_token')
 })
 it('Login', () => {
   // ...
 })
 it('Add to cart', () => {
   // ...
 })
  • Consider this test where we have used preserve once before each so that it may preserve session id and retains when it goes on to the next step.

Set Globally:

Cookies can be preserved globally, which will always be preserved across each test.

Preserve String:

Cypress.Cookies.defaults({
 preserve: 'session,'
})

Any cookies with the name 'session' will be preserved globally and won't be cleared after each test.

Array Preserve:

Cypress.Cookies.defaults({
 preserve: ['session,' 'api_token'],
})

Arrays of cookies can be passed so that tests will remember these cookies when they come across them.

RegExp Preserve:

Cypress.Cookies.defaults({
 preserve: /session/token/,
})

Now any cookie with this regular expression will be remembered.

Function Preserve:

Cypress.Cookies.defaults({
 preserve: (cookie) => {
 },
})

Own logic can be implemented within this body, and if the function is truthy, the cookie won't be cleared before each run of tests.