Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cy.clearLocalStorage should clear all localStorage of all domains #2573

Closed
pieterdd opened this issue Oct 8, 2018 · 35 comments
Closed

cy.clearLocalStorage should clear all localStorage of all domains #2573

pieterdd opened this issue Oct 8, 2018 · 35 comments
Labels
type: feature New feature that does not currently exist type: user experience Improvements needed for UX

Comments

@pieterdd
Copy link

pieterdd commented Oct 8, 2018

Summary of this thread so far

cy.clearLocalStorage doesn't behave the way I assumed it would. It doesn't clear all local storage. The docs have since been updated to reflect this.


Current behavior:

I was trying to write a simple test for some to do list website when I noticed that certain state wasn't being cleared correctly between tests. So I added some sanity checks like cy.clearCookies() and cy.clearLocalStorage() - which in theory should be redundant - and then I observed this: https://youtu.be/x6Yeh6WM5fM

Oddly enough, it looks like local state is magically reappearing for reasons I don't understand. Any idea what's going on? Here's the code snippet I executed:

describe('Hello world', () => {
    before(function () {
        cy.viewport(1200, 660)
        cy.clearCookies()
        cy.clearLocalStorage()
        cy.wait(20000)
        cy.visit('https://www.any.do/').contains('Login').click()
        cy.contains('ALREADY A MEMBER?', {
            'timeout': 10000
        }).click()
        cy.get('#emailSignin #email').type('[email protected]')
        cy.get('#emailSignin #password').type('badpassword')
        cy.contains('SIGN IN').click()
    })

    it('Is a test', () => {
        cy.log('Look!')
    })
})

Even going into the developer tools, Application tab, clicking 'Clear storage' and then clearing everything doesn't reset it. The only workaround I have found is selecting the local storage data for https://web.any.do and clicking 'Clear All'.

Desired behavior:

The old local storage data should not reappear when the test reaches the domain https://web.any.do.

Steps to reproduce:

  1. Run this script with valid credentials. I've changed my example account's password, but you can use [email protected] with password 'anydone'. The script should work even without the cy.wait; that was just to give me time to inspect cookie/local storage beforehand.
  2. The test will pass.
  3. Rerun the test.
  4. The test will fail because it suddenly remembers the login.

Versions

Cypress v3.1.0, Electron 59

@jennifer-shehane
Copy link
Member

I believe what is happening is that when Cypress clears localStorage, it only clears local storage for the domain and subdomain that was used in cy.visit(), so you will see localStorage cleared for https://www.any.do/ but not for https://web.any.do.

@brian-mann if you can confirm this is the current behavior -

  1. I would like to specify this in our documentation
  2. Is it possible for us to clear localStorage on other subdomains/domains?

@pieterdd
Copy link
Author

Interesting... if this is correct it'd definitely be good to add to the documentation. But ideally I'd like all local storage to be cleared by this command (or a similar one).

@jennifer-shehane
Copy link
Member

Yes, I did a test to verify this is the behavior - that cy.clearLocalStorage() only clears for the current domain (including subdomain).

cy.clearCookies() has a similar issue open here: #408

it('opens the page', function () {
  cy.visit('https://www.cypress.io').then((win) => {
    win.localStorage.setItem('foo', 'bar')
    expect(win.localStorage.getItem('foo')).to.eq('bar')
  })
  cy.visit('https://www.cypress.io/dashboard/').then((win) => {
    expect(win.localStorage.getItem('foo')).to.eq('bar')
  })
  cy.visit('https://docs.cypress.io').then((win) => {
    expect(win.localStorage.getItem('foo')).to.eq('bar') // fails
  })
})

I created a new issue in our docs to document cy.clearLocalStorage only clearing it for the current domain here: cypress-io/cypress-documentation#1034. Our documentation is open source and contributions are welcome. 😄

@jennifer-shehane jennifer-shehane changed the title Local storage reappearing between tests cy.clearLocalStorage should clear all localStorage of all domains Oct 10, 2018
@jennifer-shehane jennifer-shehane added the type: feature New feature that does not currently exist label Oct 10, 2018
@pieterdd
Copy link
Author

Thank you for your analysis!

I see that a documentation update has already been released. Assuming I'm able to figure out how to alter the behavior of cy.clearLocalStorage so that it clears everything, would you and the other maintainers be open to that? Or is there a specific reason for the current behavior?

@jennifer-shehane
Copy link
Member

Oh, yes, we agree it should clear localStorage for all domains, or at least be controllable in some way to choose which domains they're cleared for.

@pieterdd
Copy link
Author

I'm having lots of trouble setting up a development environment for the cypress repo (the npm install command fails), so I think I'll leave this code change up to you guys.

In the meantime, is there some sort of workaround you'd recommend? I'm assuming it's best to call cy.visit and then run cy.clearLocalStorage or win.localStorage.clear for every website I'd like to clear the storage of?

@cypress-bot cypress-bot bot added the stage: ready for work The issue is reproducible and in scope label Feb 28, 2019
@vikasg52
Copy link

vikasg52 commented Sep 5, 2019

I am also having similar issue - Cypress not clearing the localStorage using cy.clearLocalStorage().

Any update- when are we going to fix it?

@emilKobberholm

This comment has been minimized.

@swathisham

This comment has been minimized.

@ghost

This comment has been minimized.

@BirgitPohl
Copy link

So I have cy.visit() on a beforeEach and the cy.clearLocalStorage() on the actual test. In this case.
It clearly does not reflect, what it says and I'm having a little staging/production miss-match:
I wonder, if there is a way to clear cookies and local storage when ending the browser as one might need a clean browser to start the tests.

@benjaminbours
Copy link

I really need this feature as well. I was looking at the codebase of the function, but I'm not an expert of coffee script and it seems like it is the same as adding a custom command. So I rather tried to implement it in my project. My idea was to use the window.frames or to select all the iframes in the page to execute the localStorage.clear() on every window. But it doesn't seems to work, I don't know why.

Maybe you can tell me why this approach is apparently wrong and how should I approach it so everyone can have this feature, which is by the way, very needed in case of OAuth.

Thank you in advance the Cypress team 👍

@cjost1988
Copy link

cjost1988 commented Aug 24, 2020

Hi,

I came across with another issue where this needs to be addressed: Cookie Consent Management.
Would be glad if there is any solution around this?
Otherwise I've the feeling this is a dealbreaker :S

Cheers and ty for the nice testing environment.

@anirudhmurali
Copy link

Any update on this?

@zeptonaut
Copy link

I'm curious how this interacts with the documentation on cy.clearLocalStorage:

Cypress automatically runs this command before each test to prevent state from being shared across tests. You shouldn’t need to use this command unless you’re using it to clear localStorage inside a single test.

I'm seeing behavior where adding a global:

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

is changing a test from flaky to not flaky. Specifically, it looks like there are stale login tokens hanging around in localStorage between tests. When I run the test in isolation (it.only() for only that test), it passes 100% of the time. When I run the test alongside one other test that logs in to the app (put both in a describe.only() block together), the same test fails >50% of the time.

@zeptonaut
Copy link

zeptonaut commented Oct 12, 2020

I also tried adding a:

beforeEach(() => {
  cy.visit('/');
});

based on this issue. In some tests, my team was setting local storage before visiting a URL, which I realized might be confusing given that local storage operates on a per-domain basis. In conjunction with this bug, it seemed like it was possible that this meant the local storage wasn't getting correctly cleared between tests because the local storage we were setting wasn't attached to a domain. In practice, though, that didn't matter and the test was still flaky even with that.

(In retrospec, it makes sense that this would have no effect: clearly Cypress has to have some concept of what domain to attach the local storage entries to even before a cy.visit() call, or else the entries that we were setting (e.g. login tokens) wouldn't have had the intended effects in our tests.)

@jfhector
Copy link

I'm also blocked with this issue. Anyone has found a reliable workaround?
@zeptonaut the issue description you gave matches exactly what I'm seeing.

@vldvld

This comment has been minimized.

@MLKiiwy
Copy link

MLKiiwy commented Jan 20, 2021

If you want to clear the localstorage of an iframe that is not on your domain:

  cy.get('#iframe-id', { log: false })
    .its('0.contentWindow.localStorage', { log: false })
    .then((localStorage) => localStorage.clear());

Of course this will work only with "chromeWebSecurity": false, see https://www.cypress.io/blog/2020/02/12/working-with-iframes-in-cypress/#application-with-iframe

@dominik-fielmann
Copy link

This workaround works for me:

  beforeEach(() => {
    cy.window().then((window) => {
      window.sessionStorage.clear();
      window.localStorage.clear();
    });
  });

@uweku
Copy link

uweku commented Apr 6, 2021

Awesome, @dominik-fielmann ! Your workaround worked for me, too, though I needed to "point" Cypress to the correct domain via cy.visit(...) upfront...

@ronhks
Copy link

ronhks commented Apr 28, 2021

So, after a lot of time, we realized the problem.
The cy.clearLocalStorage() cleans only the local storage under the baseUrl definition.
If you would like to open multiple pages, you have to explicit define the clearing in the cy.visit() call, like that:

    cy.visit('subdomain.another.domain', {
      onBeforeLoad(win) {
        win.localStorage.clear();
      },
    });

I hope, this workaround helps.

@jacktomlinson
Copy link

Been trying this workaround but no luck yet... trying to clear a particular local storage value of a Typeform survey. The local storage items are set against https://companyname.typeform.com which isn't an actual page you can visit.

Tried your workaround above @ronhks but in my scenario https://companyname.typeform.com just redirects to https://typeform.com if you try to visit it in the test and therefore doesn't clear the local storage.

Any ideas?

@ronhks
Copy link

ronhks commented May 4, 2021

@jacktomlinson: in this case, can you tried to delete exactly the spcified local storage?
You can specify it in the cy.localStorage.clear(<APP_DEFINITION>)?

@jacktomlinson
Copy link

Tried that one I believe, but it doesn't clear it as the item of local storage is not on the same domain as where I am running the test from 😞.

@denysgalyuk-epicentrm
Copy link

Hi! @jennifer-shehane . Are you planning to add the possibility to clear all storages but not the main only? Is it in the roadmap?

As you can see it clears only main domain. The additional one has data even if I close the runner. It is hardly cached. cy.clearLocalStorage() fails to clear it also.
image

@zekedvc
Copy link

zekedvc commented May 10, 2021

this issue still present. I am working with multiple logins and cleaning the local storage and cookies is not working. I couldnt find a workaround but basically I have to execute case by case instead of a complete run, has someone found a workaround?

@jacktomlinson
Copy link

This was the only workaround I have thought so far... is that if you can visit url you want to clear and wait for the page to load in a separate test before hand...

// A workaround here as typeform stores previous results on this domain in local storage.
// Read more here: https://github.com/cypress-io/cypress/issues/2573
it('should clear typeform session storage', () => {
  cy.visit('https://companyname.typeform.com/to/EP0Zx2'); // an example typeform survey
  cy.wait(4000);
  cy.clearLocalStorage();
});

Then run what you would like to in a second test case.

@LeoForLearning
Copy link

Hello, i do see this issue is open still . Any plans for a fix of this issue?
how ever the workarounds mentioned here did not help me much

@csimpi
Copy link

csimpi commented Feb 2, 2022

Facing with the same issue too

@the-bmc-dev
Copy link

I have the same issue too!

@cypress-bot cypress-bot bot added stage: backlog and removed stage: ready for work The issue is reproducible and in scope labels Apr 29, 2022
@hridyanshdugar
Copy link

Hi am facing the same issue, any helpful workaround?

@MehranShafqat
Copy link

is there any update on this, please? this is causing huge issues as when we talk about E2E testing this is common stuff and common use case :( facing huge issue due to this :(

@emilyrohrbough
Copy link
Member

The new cy.clearAllLocalStorage() command will handle clearing local storage across all origin. This will be available in Cypress 12.

@cypress-bot
Copy link
Contributor

cypress-bot bot commented Dec 6, 2022

Released in 12.0.0.

This comment thread has been locked. If you are still experiencing this issue after upgrading to
Cypress v12.0.0, please open a new issue.

@cypress-bot cypress-bot bot locked as resolved and limited conversation to collaborators Dec 6, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
type: feature New feature that does not currently exist type: user experience Improvements needed for UX
Projects
None yet
Development

No branches or pull requests