我想开玩笑地模拟localStorage方法以进行错误模拟。我在Utility.js中定义了localstorage getter和setter方法。我想模拟localStorage.setItem
在调用utility.setItem
时引发错误。
//file: utility.js
export default {
getItem(key) {
return localStorage.getItem(key);
},
setItem(key, value) {
localStorage.setItem(key, value);
}
};
开玩笑
test('throw error', () => {
localStorage.setItem = jest.fn(() => {
console.log(" called ");
throw new Error('ERROR');
});
utility.setItem('123', 'value');
});
但是localStorage.setItem
模拟永远不会被调用。我也尝试过
window.localStorage.setItem = jest.genMockFunction(()=>{console.log(" Mock Called")});
global.localStorage.setItem = jest.fn(()=>{console.log(" Mock Called")});
答案 0 :(得分:2)
[['a', 'b17', 'c', 'dz', 'e', 'ff', 'e3'], ['e66', 'a', 'b17', 'c', 'dz', 'e', 'ff'], ['e3', 'e66', 'a', 'b17', 'c', 'dz', 'e'], ['ff', 'e3', 'e66', 'a', 'b17', 'c', 'dz'], ['e', 'ff', 'e3', 'e66', 'a', 'b17', 'c']]
根本不需要其他任何东西,如此处所述:https://github.com/facebook/jest/issues/6798#issuecomment-440988627
答案 1 :(得分:1)
如果您想测试localStorage函数,那么我想建议一个this好的npm软件包。
按照文档在安装测试文件中配置此程序包后,您可以在此之后执行此操作。
test('should save to localStorage', () => {
const KEY = 'foo',
VALUE = 'bar';
dispatch(action.update(KEY, VALUE));
expect(localStorage.setItem).toHaveBeenLastCalledWith(KEY, VALUE);
expect(localStorage.__STORE__[KEY]).toBe(VALUE);
expect(Object.keys(localStorage.__STORE__).length).toBe(1);
});
test('should have cleared the sessionStorage', () => {
dispatch(action.reset());
expect(sessionStorage.clear).toHaveBeenCalledTimes(1);
expect(sessionStorage.__STORE__).toEqual({}); // check store values
expect(sessionStorage.length).toBe(0); // or check length
});
答案 2 :(得分:1)
要访问被测模块的全局范围内的内容,您需要使用global
名称空间。因此,使用localStorage
来访问global.localStorage
:
global.storage = {
store:{},
getItem(key)=>this.store[key],
setItem: (key, value)=> this.store[key] = value
}
答案 3 :(得分:0)