问题描述
我正在尝试为我的所有JS编写测试,并且测试(我使用的是Jasmine)在浏览器中本地运行。由于安全限制(?)sessionStorage在Firefox中不能在本地工作(在浏览器中查看文件:/// ...)。
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.
快速示例:
window.sessionStorage.setItem('foo', 'bar');
这给出了错误:不支持操作。
This gives "Error: Operation is not supported".
我尝试用我自己的模拟方法覆盖window.sessionStorage,但没有运气。
I tried overriding window.sessionStorage with my own mock methods, but with no luck.
我目前唯一的解决办法就是把所有相关的东西都放在一起到try / catch块中的sessionStorage。
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?
推荐答案
Object.defineProperty
似乎可以使用它,你可以模拟 sessionStorage
使用它:
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);
但此模型不适用于<$ c的索引器 $ c> sessionStorage ( window.sessionStorage [key] = value
)以构建模型
对象。
but this mockup doesn't work with the indexer of sessionStorage
(window.sessionStorage[key] = value
) Proxy to build the mockup
object.
这篇关于如何在FF本地处理sessionStorage(用于测试)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!