JSDom 11.12.0 - how to mock localStorage?

↘锁芯ラ 提交于 2020-08-04 06:33:27

问题


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.


回答1:


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.




回答2:


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

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




回答3:


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.



来源:https://stackoverflow.com/questions/51569521/jsdom-11-12-0-how-to-mock-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!