Javascript 切换navigator.online
我正在使用phantomjs运行与karma的集成测试。如何模拟脱机模式 似乎我无法更改“navigator.online”,并且在phantomjs的脱机模式下找不到任何内容 编辑: 应用程序正在向外部位置发送消息。当浏览器脱机时,它应该停止发送消息并将其存储在队列中。一旦连接恢复,它应该从队列发送所有消息 我只是检查“navigator.online”是否返回true或false 也许有更好的方法来实现和测试这一点Javascript 切换navigator.online,javascript,phantomjs,karma-runner,Javascript,Phantomjs,Karma Runner,我正在使用phantomjs运行与karma的集成测试。如何模拟脱机模式 似乎我无法更改“navigator.online”,并且在phantomjs的脱机模式下找不到任何内容 编辑: 应用程序正在向外部位置发送消息。当浏览器脱机时,它应该停止发送消息并将其存储在队列中。一旦连接恢复,它应该从队列发送所有消息 我只是检查“navigator.online”是否返回true或false 也许有更好的方法来实现和测试这一点 如果您有任何建议,我们将不胜感激。navigator.online为只读属性
如果您有任何建议,我们将不胜感激。
navigator.online
为只读属性。您的组件应该有一个单独的属性,以便您可以在测试中将其设置为false或true(而不是总是直接检查navigator.online
)
课程:如果可以的话,不要在代码中使用全局对象,这会使模拟变得更加困难。相反,允许调用方模拟/存根全局对象。这是我用来控制测试中的
navigator.onLine
方法的代码。我在使用Karma运行的测试中使用它来启动浏览器并启动测试。摩卡是真正的试跑者。以下内容在before
(akabeforeAll
)钩子中运行。整个事情(包括让在线
)的范围是需要它的描述
块
我使用两种方法,因为不幸的是,没有办法修改navigator
,使其在任何地方都能工作。第一种方法适用于Chrome、Firefox、IE、Edge和Opera。第二种方法适用于Safari。相反,第二种方法不适用于铬。因此,我们不能只使用一种或另一种方法
let onLine = true;
function mockNavigatorOnline() {
const descriptor = {
get: function getOnline() {
return onLine;
},
};
// 1st method.
Object.defineProperty(navigator.constructor.prototype, "onLine",
descriptor);
// Check whether the code above "took". We check both for `true`
// and `false`.
onLine = false;
let passes = navigator.onLine === onLine;
onLine = true;
passes = passes && (navigator.onLine === onLine);
// 2nd method.
if (!passes) {
navigator = Object.create(navigator, { onLine: descriptor });
}
}
let onLine = true;
function mockNavigatorOnline() {
const descriptor = {
get: function getOnline() {
return onLine;
},
};
// 1st method.
Object.defineProperty(navigator.constructor.prototype, "onLine",
descriptor);
// Check whether the code above "took". We check both for `true`
// and `false`.
onLine = false;
let passes = navigator.onLine === onLine;
onLine = true;
passes = passes && (navigator.onLine === onLine);
// 2nd method.
if (!passes) {
navigator = Object.create(navigator, { onLine: descriptor });
}
}