Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSDom 11.12.0 - how to mock localStorage?

Since the latest release of JSDom, I'm not able to mock localStorage anymore.

I've tried the following methods:

  1. Object.defineProperty(window, 'localStorage', {value: LocalStorageMock})
  2. window.localStorage = LocalStorageMock;
  3. jest.spyOn(window.localStorage, 'setItem')

Any of those methods not worked for me, I get always the original localStorage.

like image 441
felixmosh Avatar asked Jul 28 '18 08:07

felixmosh


People also ask

Does Jest mock localStorage?

You can mock localStorage globally for React in Jest by adding the above to the setupTests. js file and adding global. localStorage under the function.

How do I test localStorage?

First of all, we need to check whether the Local Storage is used. Using Google Chrome, click on menu -> Tools -> Developer Tools. Then under Resources you will see 'Local Storage' and 'Web Storage'. Using Firefox with the Firebug add on you can easily inspect the localStorage/sessionStorage object in the DOM tab.

What is localStorage removeItem?

The removeItem() method removes the specified Storage Object item. The removeItem() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.


3 Answers

setItemSpy = jest.spyOn(Storage.prototype, 'setItem'); works for me.

Saw this fix here: https://github.com/facebook/jest/issues/6858#issuecomment-413677180

like image 77
Guilherme Vasconcelos Avatar answered Oct 25 '22 11:10

Guilherme Vasconcelos


I actually ran into this same issue when updating Jest, not sure if that's what happened to you but I found this fix here: https://github.com/facebook/jest/issues/6766

From OlivierB-OB:

As a temporary workaround you can install jsdom "11.11.0" (exact) as a dev-dependency in your package. jest-environment-jsdom should then use this version instead of the lastest "11.12.0" causing the behavior. Cheers!

After that I mocked localstorage in test setup and spying was back to normal.

And an implementation of localstorage mock: https://github.com/facebook/jest/issues/2098 lacks removeItem though, so you might need to add it.

like image 23
DuncanBb Avatar answered Oct 25 '22 11:10

DuncanBb


You can use the dom-storage package available via npm:

const Storage = require('dom-storage');
global.localStorage = new Storage(null, { strict: true });
global.sessionStorage = new Storage(null, { strict: true });

We use the latest release of jsdom for our unit tests and the above method has worked great.

like image 22
Elliot B. Avatar answered Oct 25 '22 11:10

Elliot B.