Pablo Jurado

10 May, 2021

How to mock local storage on jest

Sometimes our components interact with the local storage. When writing tests, We need a way of mocking this functionality.

The local storage is a property of the window object. That means when running our test on jest, the local storage will not be present because jest runs on a node environment.

The following object is mocking the local storage implementation. We can add this to our test or the src/setupTests.ts.

const localStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn(),
  length: 0,
  key: jest.fn(),
};

Object.defineProperty(window, "localStorage", { value: localStorageMock });

Now when testing our components, we can test the following functionality
expect(window.localStorage.setItem).toHaveBeenCalled());