【问题标题】:How to test localStorage with Jest如何使用 Jest 测试 localStorage
【发布时间】:2018-11-03 10:28:19
【问题描述】:

我已经按照关于另一个威胁的建议模拟了 localStorage,但我无法让测试正常工作,我尝试了多次都没有成功。

这是模拟

class LocalStorageMock {
  constructor() {
    this.store = {};
  }
  clear() {
    this.store = {};
  }

  getItem(key) {
    return this.store[key] || null;
  }

  setItem(key, value) {
    this.store[key] = value.toString();
  }

  removeItem(key) {
    delete this.store[key];
  }
}
这是我试图测试的功能。

const setToLS = (target, value) => {
  localStorage.setItem(target, JSON.stringify(value));
};
const saveToLS = (target, item) => {
  let items;
  if (localStorage.getItem(target)) {
    items = utilities.addItem(JSON.parse(localStorage.getItem(target)), item);
  } else {
    items = utilities.addItem([], item);
  }
  setToLS(target, items);
};

这是我无法工作的测试。

describe('utilitiesLS', () => {

  describe('saveToLS', () => {
    it('should save item to LS')', () => {
      const target = 'recipes';
      const item = { name: 'salat', ingredients: 'spinach', id: 1 };
      utilitiesLS.saveToLS(target, item)
      expect(localStorage.store).toMatch( '{"recipes": [{"id": 1, "ingredient": "spinach", "recipeName": "salat"}]}'
      )
    });
  });
});

这就是错误。

 expect(string)[.not].toMatch(expected)

    string value must be a string.
    Received: undefined

      29 |       const item = { recipeName: 'salat', ingredients: 'spinach', id: 1 };
      30 |       utilitiesLS.saveToLS(target, item)
    > 31 |       expect(localStorage.store).toMatch( '{"recipes": [{"id": 1, "ingredient": "spinach", "recipe
Name": "salat"}]}'
         |                                  ^
      32 |       )
      33 |     });
      34 |   });

【问题讨论】:

    标签: javascript html unit-testing local-storage jestjs


    【解决方案1】:

    问题在于你的测试。

    LocalStorageMock.store 是一个对象,但您的测试 expect(localStorage.store).toMatch( '{"reci... 正在测试它以查看它是否是一个字符串。这就是您的测试没有通过的原因,因为对象与字符串不匹配。

    要解决这个问题,您应该测试:

      expect(localStorage.store).toEqual({"recipes": [{"id": 1, "ingredient": "spinach", "recipeName": "salat"}]})
    

    注意到 localStorage.store 未定义表明您也没有获得您的测试正在使用的模拟的构造实例。

    n.b.如果您尝试模拟本地存储,请考虑使用预先构建、测试和记录的方法之一,例如: https://www.npmjs.com/package/jest-localstorage-mock

    【讨论】:

    • 我也试过了,我收到了。 expect(string)[.not].toMatch(expected) 字符串值必须是字符串。收到:未定义
    • 我已经更新了对象的匹配器(应该是 toEqual)——你需要你的 localStorage 到你的测试中吗?
    • 是的,我仍然返回未定义。期望值等于:{“recipes”:[{“id”:1,“ingredient”:“spinach”,“recipeName”:“salat”}]} 收到:未定义差异:比较两种不同类型的值。预期的对象,但收到未定义。
    • 如果没有详细说明如何注入模拟(可能是您关注的线程的链接),很难确切知道出了什么问题;虽然看起来你的测试和你的函数有不同的模拟实例。但是,已经有针对此问题的预构建解决方案 - 我添加了指向我的答案的链接。
    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 2021-08-11
    • 2017-11-11
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    相关资源
    最近更新 更多