1

It seems I can't set local storage in Cypress? When I get the item from local storage it is different to what I have set (it always returns the default value)

Am I setting the storage incorrectly?

  beforeEach(() => {
    cy.clearLocalStorage();
    cy.clearCookies();
    window.localStorage.setItem('One', 'NL');
    window.localStorage.setItem('Two', 'NL');
    window.localStorage.setItem('Three', 'NL');
    visitPage('/');

    cy.window().then((win) => {
      const myItemOne = win.localStorage.getItem('One');
      const myItemTwo = win.localStorage.getItem('Two');
      const myItemThree = win.localStorage.getItem('Three');
      cy.log(myItemOne, myItemTwo, myItemThree);
    });

Should return log NL, NL, NL, but returns SE, SV, SV

2 Answers2

3

The localstorage object is the same for all windows in the browser, it doesn't matter if you use window or cy.window().

cy.clearCookies();
cy.clearLocalStorage()
  .then(() => {
    window.localStorage.setItem('One', 'NL');
    window.localStorage.setItem('Two', 'NL');
    window.localStorage.setItem('Three', 'NL');
  })

cy.visit('/')
  .then(() => {
    const myItemOne = window.localStorage.getItem('One');
    const myItemTwo = window.localStorage.getItem('Two');
    const myItemThree = window.localStorage.getItem('Three');
    expect([myItemOne, myItemTwo, myItemThree]).to.deep.equal(['NL','NL','NL'])
  })
1

Setting local storage variables via window.localStorage.setItem() is a synchronous command, whereas your Cypress commands (such as cy.clearLocalStorage()) are asynchronous. This means that they probably are not executing in the order you write them. If you wrap setting your localStorage items within the Cypress command chain, they should be set appropriately.

cy.clearLocalStorage();
cy.clearCookies();
cy.window().then((win) => {
  win.localStorage.setItem('One', 'NL');
  win.localStorage.setItem('Two', 'NL');
  win.localStorage.setItem('Three', 'NL');
});
visitPage('/');
agoff
  • 5,818
  • 1
  • 7
  • 20