开玩笑模拟localStorage方法 [英] Jest mock localStorage methods
本文介绍了开玩笑模拟localStorage方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想开玩笑地模拟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")});
推荐答案
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 的讨论也很有帮助.
这篇关于开玩笑模拟localStorage方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文