cypress icon indicating copy to clipboard operation
cypress copied to clipboard

getAllLocalStorage returns empty object even when key value pairs are set

Open farlandlee opened this issue 2 years ago • 2 comments
trafficstars

Current behavior

running is little test:

cy.visit('https://example.cypress.io', {
          onBeforeLoad(win) {
              win.localStorage.setItem('key', 'value')
          },
      })
      cy.window().its('localStorage', { timeout: 5000 }).should('have.property', 'key')
      cy.getAllLocalStorage().then((result) => {
          expect(result).to.deep.equal({
                'https://example.cypress.io': {
                key: 'value',
              },
          })
      })
  })

the assertion that key is set succeeds, but then using get getAllLocalStorage() yields this error: expected {} to deeply equal { Object (https://example.cypress.io) }

Desired behavior

cypress should return all localStorage key values that have been set grouped by url.

Test code to reproduce

Here is my repo: https://github.com/farlandlee/cypress-test-tiny

The code is lifted from https://docs.cypress.io/api/commands/getalllocalstorage#Get-all-localStorage and then I added the assertion about the localStorage key being set.

Cypress Version

12.3.0

Node version

v16.18.1

Operating System

macOs 13.1 (22C65)

Debug Logs

too long to paste, but here is an excerpt:
  cypress:server:reporter got mocha event 'end' with args: [ { end: '2023-01-09T15:00:33.509Z' } ] +0ms
  1) testing localStorage
       should set then read localStorage:

      AssertionError: expected {} to deeply equal { Object (https://example.cypress.io) }
      + expected - actual

      -{}
      +{ 'https://example.cypress.io': { key: 'value' } }

      at Context.eval (webpack:///./cypress/e2e/spec.cy.js:15:33)

Other

No response

farlandlee avatar Jan 09 '23 15:01 farlandlee

Thanks for reporting this issue and providing a reproduction.

It looks like this is an issue if the key is collides with any method or property that's a part of the localStorage (or sessionStorage) API. In this case, key is a method on localStorage, so it doesn't appear in the object read from window.localStorage when we access it here or here.

We should be able to fix this by using Object.keys() or Object.entries() instead of relying on the static value of window.localStorage.

chrisbreiding avatar Jan 10 '23 14:01 chrisbreiding

This issue has not had any activity in 180 days. Cypress evolves quickly and the reported behavior should be tested on the latest version of Cypress to verify the behavior is still occurring. It will be closed in 14 days if no updates are provided.

cypress-app-bot avatar Jul 10 '23 02:07 cypress-app-bot