我无法正确模拟对象方法:
const getItem = jest.fn(key => key);
localStorage = {
getItem
};
console.log(getItem('test')); // 'test'
console.log(localStorage.getItem('test')); // null
以防万一变量名出现问题,我在评论以上内容后尝试了此操作:
localStorage = jest.fn(key => key);
console.log(localStorage('test2')); // 'test2'
在目标文件中,我将对象和属性分配给了全局对象,因为我发现它可以与fetch
一起使用:
// target file used by the test runner file:
if (typeof window !== 'undefined') {
fetch = window.fetch;
localStorage = window.localStorage;
localStorage.getItem = window.localStorage.getItem;
} else {
fetch = global.fetch;
localStorage = global.localStorage;
localStorage.getItem = global.localStorage.getItem;
}
也尝试过
ES5属性分配(getItem:getItem)。没变化
const getItem = jest.fn(key => key);
global.localStorage = {
getItem
};
console.log(global.localStorage.getItem('test')); // null
它也记录没有全局的null。在log参数中。
还有什么会阻止localStorage.getItem()正常工作?