问题
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.
回答1:
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 whitelist 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({
  whitelist: "session_id"
})
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)
  }
}
    回答2:
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/<some_command>.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
回答3:
Here is the solution that worked for me:
 Cypress.LocalStorage.clear = function (keys, ls, rs) {
    return;
 before(() => {
    LocalStorage.clear();
    Login();
  })
Control of cookie clearing is supported by Cypress: https://docs.cypress.io/api/cypress-api/cookies.html
回答4:
You can add your own login command to Cypress, and use the cypress-localstorage-commands package to persist localStorage between tests.
In support/commands:
import "cypress-localstorage-commands";
Cypress.Commands.add('loginAs', (UserEmail, UserPwd) => {
  cy.request({
    method: 'POST',
    url: "/loginWithToken",
    body: {
      user: {
        email: UserEmail,
        password: UserPwd,
      }
    }
  })
    .its('body')
    .then((body) => {
      cy.setLocalStorage("accessToken", body.accessToken);
      cy.setLocalStorage("refreshToken", body.refreshToken);
    });
});
Inside your tests:
describe("when user FOO is logged in", ()=> {
  before(() => {
    cy.loginAs("foo@foo.com", "fooPassword");
    cy.saveLocalStorage();
  });
  beforeEach(() => {
    cy.visit("/your-private-page");
    cy.restoreLocalStorage();
  });
  it('should exist accessToken in localStorage', () => {
    cy.getLocalStorage("accessToken").should("exist");
  });
  it('should exist refreshToken in localStorage', () => {
    cy.getLocalStorage("refreshToken").should("exist");
  });
});
    回答5:
Here is the useful link that solves my problem like yours: Preserve cookies through multiple tests
my code like:
const login = () => {
    cy.visit('http://0.0.0.0:8080/#/login');
    cy.get('#username').type('username');
    cy.get('#password').type('1234password$');
    cy.get('#login-button').click();
}
describe('UI', () => {
  // beforeEach(login);
    beforeEach(() => {
        login();
        Cypress.Cookies.preserveOnce('session_id', 'remember_token');
  });
});
hope can help you.
来源:https://stackoverflow.com/questions/50471047/preserve-cookies-localstorage-session-across-tests-in-cypress