如何用Jest模拟localforage.getItem() ?



我正在使用localforage编写代码测试,并且我一遍又一遍地获得undefined (reading 'getItem')!

  • App.test.tsx
test('render App component', () => {
jest.mock('localforage', () => ({
getItem: (item: string) => {
return { name: 'John' };
},
}));
render(<App />);
});

but in vain…

● render App component
TypeError: Cannot read properties of undefined (reading 'getItem')
124 |
125 |   useEffect(() => {
> 126 |     localforage.getItem('20220622').then((values) => console.table(values));
|                 ^
127 |   }, []);
128 |
  • App.tsx
const App = () => {
useEffect(() => {
localforage.getItem('20220622').then((values) => console.table(values));
}, []);
return (<p>Hello.</p>);
}

您可以通过在根__mocks__文件夹中创建localforage.ts文件来模拟此操作。在这里,您可以模拟这个模块中的任何值或函数,Jest将自动使用它。

// <rootDir>/__mocks__/localforage.ts
const mock = {
setItem: async () => undefined,
getItem: async () => undefined,
removeItem: async () => undefined,
};
export default mock;

文档

最新更新