Stay logged during a test session in Cypress

EL BEHEDY Ramy
2 min readDec 30, 2020

Environment

Currently I’m working on an internal web tool for my company, and a few days ago I was assigned to a test refactoring task on Cypress.

My task was to speed up these tests and make them more efficient. I noticed that for each step of the test that was launched, Cypress disconnected our session and asked for a new one each time.

Our solution uses local variables to keep a valid session and after several searches I found a way to keep a session active to test several cases without logging out.

One thing to know is that Cypress cleans up cookies and local variables every time it(), context() methods or tests are run.

1st step : commands.js

We will need to create two helpers commands which save and restore the local storage between in the command.js file inside the support folder.

cypress/support/<some_command>.js

Create variable LOCAL_STORAGE_MEMORY :

let LOCAL_STORAGE_MEMORY = {};

Save local storage :

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

Restore local storage :

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

2nd step : beforeEach() and afterEach()

Now that our methods have been created, all that remains is to insert them before and after each test case.

beforeEach() :

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

afterEach() :

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

And Voilà !

Sources

If you have encountered problems or want more information, you can check out the different sources where I found this solution :

https://github.com/cypress-io/cypress/issues/461

https://stackoverflow.com/questions/50471047/preserve-cookies-localstorage-session-across-tests-in-cypress

--

--

EL BEHEDY Ramy

Hello ! I’m Ramy, a junior software engineer based in Paris, France.