首页 > 解决方案 > 赛普拉斯 - 从夹具文件中设置本地存储值

问题描述

在开始之前,我必须将以下 JSON 数据设置到我的本地存储中,并且本地存储中的值与夹具文件中的值不完全相同。

requiredJsonData.json:

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

代码

 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'));
    })
  })
 })

结果:

在此处输入图像描述

显然,我尝试将其读取并转换为地图,但在执行相同操作时会引发另一个错误“Iterator value null is not an entry object”

我对地图的尝试:

 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);
  })

尝试使用“地图”时出错:

在此处输入图像描述

一个(肮脏的)解决方案是,在继续之前从夹具中移除位置 1 和位置 n 的 '[' 和 ']' ,它会起作用,但我不想让它变得那么血腥。

有人可以指出我遗漏了什么并帮助您了解我如何解决它吗?

标签: javascriptcypress

解决方案


在丹从评论中暗示之后,它奏效了。

更新代码:

 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);
         })
      })

在此处输入图像描述


推荐阅读