08.27.2022 - TypeScript/Testing localStorage in Jest

« All posts

One approach to testing the localStorage function in Jest is to mock the setItem/getItem methods.

To mock something with localStorage, we can do it via the Storage.prototype, for example:

jest.spyOn(Storage.prototype, 'setItem');
jest.spyOn(Storage.prototype, 'getItem');

Now, you’ll be able to test their behavior:

// test write to localStorage
expect(localStorage.setItem).toHaveBeenCalledWith('key', 'value')
// test read from localStorage

Or, use mockReturnValue method if you want to mock the return value of localStorage.getItem:

jest.spyOn(Storage.prototype, 'getItem')

Read more