skip to Main Content

Is there a way to mock localStorage with Jest?

I have tried many answers from this question however, none seemed to work on typescript as I keep getting:

"ReferenceError: localStorage is not defined"

I also tried to make my own mock setup file:

export const localStorageMock = {
  getItem: jest.fn().mockImplementation(() => ({
    data: ""
  })),

  removeItem: jest.fn().mockImplementation(() => ({
    data: ""
  })),
};

And linking it like so:

jest.mock('localStorage', () => {
  return jest.fn().mockImplementation(() => localStorageMock);
});

Is there a way to do it? I only need to use getItem and removeItem for the methods I wish to test.

2

Answers


  1. You can mock local storage like this:

    const mockLocalStorage = (() => {
      let store = {} as Storage;
    
      return {
        getItem(key: string) {
          return store[key];
        },
    
        setItem(key: string, value: string) {
          store[key] = value;
        },
    
        removeItem(key: string) {
          delete store[key];
        },
    
        clear() {
          store = {} as Storage;
        },
      };
    })();
    
    export default mockLocalStorage;
    

    Then in your test file you can set the mockLocalStorage as the local storage you want to use like this:

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

    This may not be the best way of doing this, but it’s a way that has worked for me in the past.

    Login or Signup to reply.
  2. You can simply achieve this by defining a localStorage property on windows object.

    localStorageMock.ts :

    const localStorageMock = (() => {
      let store: { [key: string]: string } = {};
    
      return {
        getItem: (key: string) => store[key] || null,
        setItem: (key: string, value: string) => {
          store[key] = value.toString();
        }
      };
    })();
    
    Object.defineProperty(window, 'localStorage', {
      value: localStorageMock,
    });
    

    Now, in your test file, import the above file localStorageMock.ts and use Jest’s function to mock the localStorage :

      import './localStorageMock.ts'; // Import the localStorage mock file
    
      it('should store value in localStorage', () => {
        // Use localStorage methods as usual
        localStorage.setItem('myKey', 'myValue');
        expect(localStorage.getItem('myKey')).toBe('myValue');
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search