How to deal with sessionStorage locally in FF (for testing)

故事扮演 提交于 2019-12-07 16:28:58

问题


I'm trying to write tests for all my JS, and the tests (I'm using Jasmine) are run locally in the browser. Due to security restraints(?) sessionStorage does not work locally (viewing file:///... in the browser) in Firefox.

Quick example:

window.sessionStorage.setItem('foo', 'bar');

This gives "Error: Operation is not supported".

I tried overriding window.sessionStorage with my own mock methods, but with no luck.

The only solution I have at the moment is to put everything related to sessionStorage inside a try/catch block.

Any suggestions for how to best handle this issue?


回答1:


Object.defineProperty seems to work with this, you can mock sessionStorage use it:

var mockup = function() {
  var table = {};
  return {
    getItem: function(key) {
      return table[key];
    },
    setItem: function(key, value) {
      table[key] = value.toString();
    },
    clear: function() {
      table = {};
    }
  };
}();
Object.defineProperty(window, 'sessionStorage', { value: mockup });
// should output "Object { getItem=function(), setItem=function(), clear=function()}"
console.log(window.sessionStorage);

but this mockup doesn't work with the indexer of sessionStorage (window.sessionStorage[key] = value) Proxy to build the mockup object.




回答2:


You get local mocking automatically if you use: http://nbubna.github.io/store/



来源:https://stackoverflow.com/questions/9428210/how-to-deal-with-sessionstorage-locally-in-ff-for-testing

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