How to mock localforage.getItem() with Jest?

701 Views Asked by At

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>);
}
1

There are 1 best solutions below

0
samuelweckstrom On

You can mock this with creating a localforage.ts file in the root __mocks__ folder. There you can mock any values or functions in this module and Jest will automatically use this.

// <rootDir>/__mocks__/localforage.ts

const mock = {
  setItem: async () => undefined,
  getItem: async () => undefined,
  removeItem: async () => undefined,
};

export default mock;

Docs