mercredi 21 juin 2017

Simulating going online/offline with JSDOM

We are working on a tutorial for the basics of offline first apps, and are using JSDOM with Tape to test our code. In our code we update the DOM so that a text node changes from saying "online" to "offline" and vice versa by attaching an event listener to the window and listening for the "online"/"offline" events, and navigator.onLine to initialise the text to online/offline. Like so:

// 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';
});

We want to use JSDOM to test that when offline the offline event fires and our text node updates to say "offline".

JSDOM has a window.navigator.onLine property, but it is read only, and we can't find a way to change it (always true). It seems that it has the online/offline events as well, but I cannot see how to get them to fire.

How can we simulate going online/offline when testing with node?

Aucun commentaire:

Enregistrer un commentaire