如何在玩笑testing中处理localStorage?

我一直在Jesttesting中得到“localStorage没有定义”,这是有道理的,但我的select是什么? 打砖墙。

在此帮助下找出它: https : //groups.google.com/forum/#!topic/ jestjs/9EPhuNWVYTg

使用以下内容设置文件:

var localStorageMock = (function() { var store = {}; return { getItem: function(key) { return store[key]; }, setItem: function(key, value) { store[key] = value.toString(); }, clear: function() { store = {}; }, removeItem: function(key) { delete store[key]; } }; })(); Object.defineProperty(window, 'localStorage', { value: localStorageMock }); 

来自@chiedo的伟大解决scheme

但是,我们使用ES2015的语法,我觉得用这种方法写得更简洁一些。

 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]; } }; global.localStorage = new LocalStorageMock; 

处理undefined值的更好方法(不包含toString() ),如果值不存在,则返回null 。 用v15, reduxredux-auth-wrappertesting了这个

 class LocalStorageMock { constructor() { this.store = {} } clear() { this.store = {} } getItem(key) { return this.store[key] || null } setItem(key, value) { this.store[key] = value } removeItem(key) { delete this.store[key] } } global.localStorage = new LocalStorageMock 

或者你只需​​要这样一个模拟包:

https://www.npmjs.com/package/jest-localstorage-mock

它不仅可以处理存储function,还可以testing商店是否被实际调用。