我想在玩笑中模拟 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
mock永远不会被调用。我也尝试过做
window.localStorage.setItem = jest.genMockFunction(()=>{console.log(" Mock Called")});
global.localStorage.setItem = jest.fn(()=>{console.log(" Mock Called")});
jest.spyOn(window.localStorage.__proto__, 'setItem');
无需任何其他操作即可使用,如下所示:https://github.com/facebook/jest/issues/6798#issuecomment-440988627
如果你想测试 localStorage 功能,那么我建议使用 jest-localstorage-mock 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
});
要访问被测模块全局范围内的内容,您需要使用
global
命名空间。因此,要访问 localStorage
,请使用 global.localStorage
:
global.storage = {
store:{},
getItem: (key)=>this.store[key],
setItem: (key, value)=> this.store[key] = value
}
这里是 TS 版本 https://github.com/facebook/jest/issues/6798#issuecomment-440988627
import { afterAll, beforeAll } from '@jest/globals';
const mockWindowProperty = <P extends keyof Window>(property: P, value: Partial<Window[P]>) => {
const { [property]: originalProperty } = window;
delete window[property];
beforeAll(() => {
Object.defineProperty(window, property, {
configurable: true,
writable: true,
value,
});
});
afterAll(() => {
window[property] = originalProperty;
});
};
export default mockWindowProperty;