我正在使用本地饲料为代码编写一个测试,并一次又一次地获得undefined (reading 'getItem')!
App.test.tsxtest('render App component', () => {
jest.mock('localforage', () => ({
getItem: (item: string) => {
return { name: 'John' };
},
}));
render(<App />);
});但徒然..。
● 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.tsxconst App = () => {
useEffect(() => {
localforage.getItem('20220622').then((values) => console.table(values));
}, []);
return (<p>Hello.</p>);
}发布于 2022-10-05 16:19:09
您可以通过在根localforage.ts文件夹中创建一个__mocks__文件来模拟这个问题。在这里,您可以模拟这个模块中的任何值或函数,Jest将自动使用该函数。
// <rootDir>/__mocks__/localforage.ts
const mock = {
setItem: async () => undefined,
getItem: async () => undefined,
removeItem: async () => undefined,
};
export default mock;https://stackoverflow.com/questions/72712818
复制相似问题