Jest 模拟 localStorage 方法 [英] Jest mock localStorage methods
问题描述
我想在玩笑中模拟 localStorage 方法以进行错误模拟.我在utility.js 中定义了localstorage getter 和setter 方法.我想模拟 localStorage.setItem
以在调用 utility.setItem
时抛出错误.
I would like to mock localStorage methods in jest for error simulation. I have localstorage getter and setter methods defined in utility.js. I would like to mock localStorage.setItem
to throw an error when utility.setItem
is called.
//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
模拟永远不会被调用.我也试过做
However localStorage.setItem
mock is never getting called. I have also tried doing
window.localStorage.setItem = jest.genMockFunction(()=>{console.log(" Mock Called")});
global.localStorage.setItem = jest.fn(()=>{console.log(" Mock Called")});
推荐答案
这与 Andreas 在答案中的建议一致,但我能够使用 存储 接口.我做了这样的事情,
This goes inline with what Andreas suggested in the answer, but i was able to mock it using Storage interface. I did something like this,
开玩笑,
test('throw error', () => {
Storage.prototype.setItem = jest.fn(() => {
console.log(" called "); // <-- was called
throw new Error('ERROR');
});
utility.setItem('123', 'value');
});
此外,这个 PR 讨论也很有帮助.
Also this PR discussion was helpful.
这篇关于Jest 模拟 localStorage 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!