React Answers

How to mock localStorage methods with Jest?

Spread the love

To mock localStorage methods with Jest, we call jest.spyOn.

For instance, we write

jest.spyOn(window.localStorage.__proto__, "setItem");

to call jest.spyOn with window.localStorage.__proto__, which is the local storage prototype.

We mock the localStorage.setItem method by calling spyOn with 'setItem' as the 2nd argument.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *