Mad*_*d-D 6 javascript local-storage reactjs jestjs
我想在玩笑中模拟 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);
}
};
Run Code Online (Sandbox Code Playgroud)
开玩笑,
test('throw error', () => {
localStorage.setItem = jest.fn(() => {
console.log(" called ");
throw new Error('ERROR');
});
utility.setItem('123', 'value');
});
Run Code Online (Sandbox Code Playgroud)
然而,localStorage.setItemmock 永远不会被调用。我也试过做
window.localStorage.setItem = jest.genMockFunction(()=>{console.log(" Mock Called")});
global.localStorage.setItem = jest.fn(()=>{console.log(" Mock Called")});
Run Code Online (Sandbox Code Playgroud)
chr*_*alz 15
jest.spyOn(window.localStorage.__proto__, 'setItem');完全不需要其他任何东西,如此处所述:https : //github.com/facebook/jest/issues/6798#issuecomment-440988627
这与安德烈亚斯在答案中的建议一致,但我能够使用存储接口来模拟它。我做了这样的事情,
开玩笑,
test('throw error', () => {
Storage.prototype.setItem = jest.fn(() => {
console.log(" called "); // <-- was called
throw new Error('ERROR');
});
utility.setItem('123', 'value');
});
Run Code Online (Sandbox Code Playgroud)
这个公关讨论也很有帮助。
| 归档时间: |
|
| 查看次数: |
13857 次 |
| 最近记录: |