Preserve cookies / localStorage session across tests in Cypress

前端 未结 6 766
抹茶落季
抹茶落季 2020-12-30 21:58

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 ever

6条回答
  •  梦毁少年i
    2020-12-30 22:09

    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)
      }
    
    }
    

提交回复
热议问题