Categories
JavaScript Answers

How to mock local storage in Jest tests?

Spread the love

To mock local storage in Jest tests, we can create our own mock local storage methods.

For instance, we write

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

to create the localStorageMock object by creating an IIFE that returns an object that manipulates the store object.

It has getItem to return store[key].

setItem sets store[key] to value converted to a string.

clear sets store to an empty object.

And removeItem removes the store property with the given key with delete.

And then we attach our mocked local storage object to window with Object.defineProperty.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.