jsdom does not include a fake local storage API, so you need to roll out your own.

Local storage fake

Here is a simple local storage fake

const fakeLocalStorage = (function() {
let store = {};

return {
getItem: function(key) {
return store[key] || null;
},
setItem: function(key, value) {
store[key] = value.toString();
},
removeItem: function(key) {
delete store[key];
},
clear: function() {
store = {};
}
};
})();

Wiring

localStorage is a read-only property of the window interface, so it is not possible to just reassign it like window.localStorage = fakeLocalStorage

Object.defineProperty(window, 'localStorage', {
value: fakeLocalStorage
});

Full working example

Simple function that uses the localStorage API

// storage.js

export function saveToStorage(value) {
window.localStorage.setItem('the-key', value);
}

Corresponding jest test

// storage.test.js

import { saveToStorage } from './storage';

const fakeLocalStorage = (function () {
let store = {};

return {
getItem: function (key) {
return store[key] || null;
},
setItem: function (key, value) {
store[key] = value.toString();
},
removeItem: function (key) {
delete store[key];
},
clear: function () {
store = {};
}
};
})();

describe('storage', () => {
beforeAll(() => {
Object.defineProperty(window, 'localStorage', {
value: fakeLocalStorage,
});
});

it('saves the key to the storage', () => {
saveToStorage('fake-value');

expect(window.localStorage.getItem('the-key')).toEqual('fake-value');
});
});