0

I had to set the following JSON data into my local storage before I start., and the value in local storage is not exactly the same as in the fixture file.

requiredJsonData.json:

[
  [
    1000001,
    {
        "name": "Marty J",
        "callSign": "-",
        "flag": null,
        "yearBuilt": null
    }
],
[
    1000002,
    {
        "name": "Boss",
        "callSign": "5VDV2",
        "flag": "TG",
        "yearBuilt": null
    } 
   ]
 ] 

Code:

 describe('example to-do app', () => {

  before(() => {
    cy.visit('https://example.cypress.io/todo')
  })

  it('sets the local storage value from fixture', () => {
    cy.fixture('requiredJsonData.json').then((value) => {
      cy.log(value);
      localStorage.setItem('entries', value);
      cy.log(localStorage.getItem('entries'));
    })
  })
 })

Result:

enter image description here

Apparently, I tried to read and convert it as a map but it throws another error "Iterator value null is not an entry object" in doing the same.

My attempt with map:

 it('gets the local storage value', () => {
    const details = new Map([localStorage.getItem('entries')]);
    // const details = new Map(localStorage.getItem('entries'));
    var detailsSpecific = details.get('1000001');
    cy.log(detailsSpecific);
  })

Error when I try with 'map':

enter image description here

One (dirty) solution is, that remove the '[' and ']' at position 1 and position n from the fixture before proceeding and it will work, but I do not want to make it that gory.

Can someone point out what am I missing and help with your expertise on how I had to fix it?

Dhamo
  • 1,171
  • 3
  • 19
  • 41
  • 1
    `Storage.setItem` [takes a `DOMString` as its second parameter](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem). try calling `JSON.stringify` before setting and `JSON.parse` after retrieving. – Dan O Aug 04 '21 at 11:25

1 Answers1

2

After Dan's hint from the comment, it worked.

Updated code:

 it('sets the local storage value from fixture', () => {
        cy.fixture('requiredJsonData.json').then((value) => {
          cy.log(JSON.stringify(value));  
          localStorage.setItem('entries', JSON.stringify(value));
          cy.log(localStorage.getItem('entries'));
          const details = localStorage.getItem('entries');
          cy.log(details);
         })
      })

enter image description here

Dhamo
  • 1,171
  • 3
  • 19
  • 41