All posts

TypeScript / Testing localStorage in Jest

Posted On 08.27.2022

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
expect(localStorage.getItem).toHaveBeenCalledWith('key')

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

jest.spyOn(Storage.prototype, 'getItem')
    .mockReturnValue(10);