Keep local storage in Cypress

Keep local storage in Cypress

When using cypress for tests, your session and local storage data will be cleared after every test. This is a good default, but might make the tests slower as the login is one of the slowest part of most applications (as the password hashing in the background takes a lot of time by design).

To prevent the clearing of the local storage (which might contain the JWT) I created two commands and put them into the commands.js.

let LOCAL_STORAGE_MEMORY = {};

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

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

I run saveLocalStorageCache after each test and restoreLocalStorageCache before each.

beforeEach(() => {
  cy.restoreLocalStorageCache();
});

afterEach(() => {
  cy.saveLocalStorageCache();
});

To get no problems between specs I've added another command to clear the cache and call it before the spec starts.

Cypress.Commands.add("clearLocalStorageCache", () => {
  localStorage.clear();
  LOCAL_STORAGE_MEMORY = {};
});
before(function() {
  cy.clearLocalStorageCache();
});