Zoo*_*ler 8 javascript testing node.js jsdom
我们正在编写离线第一个应用程序基础知识的教程,并使用带磁带的JSDOM来测试我们的代码.在我们的代码中,我们更新DOM,以便通过将事件监听器附加到窗口并监听"在线"/"离线"事件,将文本节点从"在线"更改为"离线",反之亦然,并navigator.onLine初始化文本到在线/离线.像这样:
// get the online status element from the DOM
var onlineStatusDom = document.querySelector('.online-status');
// navigator.onLine will be true when online and false when offline. We update the text in the online status element in the dom to reflect the online status from navigator.onLine
if (navigator.onLine) {
onlineStatusDom.innerText = 'online';
} else {
onlineStatusDom.innerText = 'offline';
}
// we use the 'online' and 'offline' events to update the online/offline notification to the user
// in IE8 the offline/online events exist on document.body rather than window, so make sure to reflect that in your code!
window.addEventListener('offline', function(e) {
onlineStatusDom.innerText = 'offline';
});
window.addEventListener('online', function(e) {
onlineStatusDom.innerText = 'online';
});
Run Code Online (Sandbox Code Playgroud)
我们希望使用JSDOM来测试离线事件触发时,我们的文本节点更新为"离线".
JSDOM有一个window.navigator.onLine属性,但它是只读的,我们找不到改变它的方法(总是如此).它似乎也有在线/离线事件,但我看不出如何让它们触发.
在使用节点进行测试时,我们如何模拟在线/离线?
JSDOM 11.0.0(这是我撰写此答案时的当前版本)中没有用于更改navigator.onLine或生成online和offline事件的规定。
但是,您可以接管navigator.onLine它并自行生成事件。这是一个概念证明:
const { JSDOM } = require("jsdom");
const { window } = new JSDOM();
class OnlineController {
constructor(win) {
this.win = win;
this.onLine = win.navigator.onLine;
// Replace the default onLine implementation with our own.
Object.defineProperty(win.navigator.constructor.prototype,
"onLine",
{
get: () => {
return this.onLine;
},
});
}
goOnline() {
const was = this.onLine;
this.onLine = true;
// Fire only on transitions.
if (!was) {
this.fire("online");
}
}
goOffline() {
const was = this.onLine;
this.onLine = false;
// Fire only on transitions.
if (was) {
this.fire("offline");
}
}
fire(event) {
this.win.dispatchEvent(new this.win.Event(event));
}
}
window.addEventListener("offline", function () {
console.log("gone offline");
});
window.addEventListener("online", function () {
console.log("gone online");
});
const cont = new OnlineController(window);
console.log("online?", window.navigator.onLine);
cont.goOffline();
console.log("online?", window.navigator.onLine);
cont.goOnline();
console.log("online?", window.navigator.onLine);
Run Code Online (Sandbox Code Playgroud)
如果运行该文件,您应该得到:
online? true
gone offline
online? false
gone online
online? true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |