Preserve cookies / localStorage session across tests in Cypress

前端 未结 6 798
抹茶落季
抹茶落季 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条回答
  •  不知归路
    2020-12-30 22:10

    To update this thread, there is already a better solution available for preserving cookies (by @bkucera); but now there is a workaround available now to save and restore local storage between the tests (in case needed). I recently faced this issue; and found this solution working.

    This solution is by using helper commands and consuming them inside the tests,

    Inside - cypress/support/.js

    let LOCAL_STORAGE_MEMORY = {};
    
    Cypress.Commands.add("saveLocalStorage", () => {
      Object.keys(localStorage).forEach(key => {
        LOCAL_STORAGE_MEMORY[key] = localStorage[key];
      });
    });
    
    Cypress.Commands.add("restoreLocalStorage", () => {
      Object.keys(LOCAL_STORAGE_MEMORY).forEach(key => {
        localStorage.setItem(key, LOCAL_STORAGE_MEMORY[key]);
      });
    });
    

    Then in test,

    beforeEach(() => {
      cy.restoreLocalStorage();
    });
    
    afterEach(() => {
      cy.saveLocalStorage();
    });
    

    Reference: https://github.com/cypress-io/cypress/issues/461#issuecomment-392070888

提交回复
热议问题