如何在JavaScript单元测试中模拟localStorage

如何在JavaScript单元测试中模拟localStorage

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

问题描述

限时删除!!

那里有没有库来模拟 localStorage

我一直在使用我的大多数其他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. ??????

  1. Create wrapping functions that all my code uses and mock those
  2. Create some sort of (might be complicated) state management (snapshot localStorage before test, in cleanup restore snapshot) for 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:

beforeEach(function () {
  var store = {};

  spyOn(localStorage, 'getItem').andCallFake(function (key) {
    return store[key];
  });
  spyOn(localStorage, 'setItem').andCallFake(function (key, value) {
    return store[key] = value + '';
  });
  spyOn(localStorage, 'clear').andCallFake(function () {
      store = {};
  });
});

如果要在所有测试中模拟本地存储,请声明 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:31