Search code examples
cookiestokencypress

Preserve cookies / localStorage session across tests in Cypress


I want to save/persist/preserve a cookie or localStorage token that is set by a cy.request(), so that I don't have to use a custom command to login on every test. This should work for tokens like jwt (json web tokens) that are stored in the client's localStorage.


Solution

  • From the Cypress docs

    For persisting cookies: By default, Cypress automatically clears all cookies before each test to prevent state from building up.

    You can configure specific cookies to be preserved across tests using the Cypress.Cookies api:

    // now any cookie with the name 'session_id' will
    // not be cleared before each test runs
    Cypress.Cookies.defaults({
      preserve: "session_id"
    })
    

    NOTE: Before Cypress v5.0 the configuration key is "whitelist", not "preserve".

    For persisting localStorage: It's not built in ATM, but you can achieve it manually right now because the method thats clear local storage is publicly exposed as Cypress.LocalStorage.clear.

    You can backup this method and override it based on the keys sent in.

    const clear = Cypress.LocalStorage.clear
    
    Cypress.LocalStorage.clear = function (keys, ls, rs) {
      // do something with the keys here
      if (keys) {
        return clear.apply(this, arguments)
      }
    
    }