如何在 JavaScript 单元测试中模拟 localStorage? [英] How to mock localStorage in JavaScript unit tests?

查看:26
本文介绍了如何在 JavaScript 单元测试中模拟 localStorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何库可以模拟 localStorage?

Are there any libraries out there to mock localStorage?

我一直在使用 Sinon.JS 进行其他大部分 javascript 模拟和发现它真的很棒.

I've been using Sinon.JS for most of my other javascript mocking and have found it is really great.

我的初步测试表明 localStorage 拒绝在 firefox (sadface) 中分配,所以我可能需要解决这个问题:/

My initial testing shows that localStorage refuses to be assignable in firefox (sadface) so I'll probably need some sort of hack around this :/

我目前的选择(如我所见)如下:

My options as of now (as I see) are as follows:

  1. 创建我所有代码使用的包装函数并模拟这些函数
  2. 为 localStorage 创建某种(可能很复杂)状态管理(测试前的快照 localStorage,在清理恢复快照中).
  3. ??????

您如何看待这些方法?您认为还有其他更好的方法来解决这个问题吗?无论哪种方式,我都会把我最终在 github 上制作的结果库"放在开源的优点上.

What do you think of these approaches and do you think there are any other better ways to go about this? Either way I'll put the resulting "library" that I end up making on github for open source goodness.

推荐答案

这里有一个用 Jasmine 模拟的简单方法:

Here is a simple way to mock it with Jasmine:

let localStore;

beforeEach(() => {
  localStore = {};

  spyOn(window.localStorage, 'getItem').and.callFake((key) =>
    key in localStore ? localStore[key] : null
  );
  spyOn(window.localStorage, 'setItem').and.callFake(
    (key, value) => (localStore[key] = value + '')
  );
  spyOn(window.localStorage, 'clear').and.callFake(() => (localStore = {}));
});

如果您想在所有测试中模拟本地存储,请在测试的全局范围内声明上面显示的 beforeEach() 函数(通常的位置是 specHelper.js 脚本).

If you want to mock the local storage in all your tests, declare the beforeEach() function shown above in the global scope of your tests (the usual place is a specHelper.js script).

这篇关于如何在 JavaScript 单元测试中模拟 localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆