DEV Community

Discussion on: How to preserve localStorage between Cypress tests

Collapse
 
gsaran profile image
gsaran • Edited

Hello,

I am using this plugin to preserve local storage between tests but I am seeing different behavior when I execute e2e tests using cypress open or cypress run.

I have say 2 test files:

  • 1.test.ts which has describe block with multiple it tests & using above commands to preserve localStorage i.e. beforeEach calling cy.restoreLocalStorage() & afterEach calling cy.saveLocalStorage. In this file, I perform login & want to use local storage values in next test file.

  • 2.test.ts which also has describe block with multiple it tests & have beforeEach calling cy.restoreLocalStorage() & afterEach calling cy.saveLocalStorage()

When I run cypress open, I could see that localStorage set by 1.test.ts is restored for 2.test.ts in it's beforeEach.

But when I run cypress run or cypress run --browser chrome --headless, 2.test.ts beforeEach gets empty localStorage.

Are there any additional changes required to make it work?

Collapse
 
geabby profile image
geabby • Edited

I have a similar requirement in order to prevent repeated logins across specs. The only solution I could think of was to write the token into a file and read it again next time we login. Didn't want to go down that path yet. Were you able to find a solution to this?

Collapse
 
gsaran profile image
gsaran

Hey!
No I couldn't find a way to accomplish that.

When I ran cypress run --browser chrome --headed, I observed that new browser (incognito) window was opening for each test file. Although I was doing cy.saveLocalStorage, local storage was cleared when the browser window was closed.

So I re-organized my tests so that I can test multiple related scenarios as part of one test file, logging in the start & logging out in the last test. Within each test file I do login & logout process & that's working fine.

Thread Thread
 
javierbrea profile image
Javier Brea

Hi @gsaran and @geabby ,
The version v2.2.0 of the plugin already supports preserving localStorage across spec files. The only requirement is to install the plugin's Node events, you can checkout its installation docs for further info.

Thread Thread
 
panoshlk9 profile image
panoshlk9

That's brilliant. I was looking for that for a long long time. Thanks so much