我正在使用phantomjs与业力进行集成测试。我如何模拟离线模式?切换导航。在线
看来我无法更改'navigator.online',并且我无法在幻灯片的离线模式下找到任何内容。
编辑:
应用程序正在发送消息到外部位置。当浏览器离线时,它应该停止发送消息并将它们存储在队列中。一旦连接恢复,它应该发送队列中的所有消息。
我只是简单地检查'navigator.online'是否返回false。
也许有更好的方法来实现和测试这个。
任何意见,将不胜感激。
我正在使用phantomjs与业力进行集成测试。我如何模拟离线模式?切换导航。在线
看来我无法更改'navigator.online',并且我无法在幻灯片的离线模式下找到任何内容。
编辑:
应用程序正在发送消息到外部位置。当浏览器离线时,它应该停止发送消息并将它们存储在队列中。一旦连接恢复,它应该发送队列中的所有消息。
我只是简单地检查'navigator.online'是否返回false。
也许有更好的方法来实现和测试这个。
任何意见,将不胜感激。
navigator.online
是只读属性。你的组件应该有一个单独的属性,所以你可以在测试中,它设置为虚假或真实的(而不是总是检查navigator.online
直接)
function Storer() {}
Storer.prototype.isOnline = true;
Storer.prototype.store = function() {
// Instead of reading navigator.isOnline
if (this.isOnline) {
this.sendAjax();
} else {
this.storeLocally();
}
}
// In your tests, you can modify isOnline
var storer = new Storer();
storer.isOnline = false;
storer.setSomething();
storer.store();
// Pseudo code here
expect(store.getLocalCache()).notToBeEmpty();
storer.isOnline = false;
store.setSomethingElse();
store.store();
// Pseudo code here
expect(storer.sendAjax).toHaveBeenCalledWith("some", "arg")
课:如果你能做到不使用全局对象在你的代码,它使它更难嘲笑。相反,允许你的全局对象被调用者嘲笑/存根。
这是我用来控制测试中的navigator.onLine
方法的代码。我在Karma运行的测试中使用它来启动浏览器并开始测试。摩卡是实际的测试跑者。以下是在before
(又名beforeAll
)钩子中运行。整个事件(包括let onLine
)的作用域为需要它的describe
块。
我使用两种方法,因为不幸的是,无法以无处不在的方式修改navigator
。第一种方法适用于Chrome,Firefox,IE,Edge和Opera。第二种方法在Safari中工作。相反,第二种方法在Chrome中不起作用。所以我们不能只使用一种方法或其他方法。
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 });
}
}