I'm writing a test for code using localforage, and I'm getting undefined (reading 'getItem') over and over again!
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>);
}
You can mock this with creating a
localforage.tsfile in the root__mocks__folder. There you can mock any values or functions in this module and Jest will automatically use this.Docs