问题
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