Zborchik Chehow Zborchik Chehow - 10 months ago 85
Javascript Question

Toggle navigator.online

I am running integration tests with karma using phantomjs. How can I simulate offline mode?

It seems that I cannot change 'navigator.online' and I couldn't find anything on offline mode for phantomjs.


Application is sending messages to external location. When browser goes offline it should stops sending messages and store them in queue. Once connection is restored it should send all messages from queue.

I am simply checking either 'navigator.online' returns true of false.

Maybe there is a better way to implement and test this.

Any advice would be appreciated.


navigator.online is a readonly property. Your components should have a separate property so you can set it to false or true in tests (instead of always checking navigator.online directly)

function Storer() {}
Storer.prototype.isOnline = true;

Storer.prototype.store = function() {
    // Instead of reading navigator.isOnline
    if (this.isOnline) {
    } else {

// In your tests, you can modify isOnline
var storer = new Storer();
storer.isOnline = false;
// Pseudo code here

storer.isOnline = false;
// Pseudo code here
expect(storer.sendAjax).toHaveBeenCalledWith("some", "arg")

Lesson: Don't use global objects in your code if you can, it makes it harder to mock. Instead, allow your global objects to be mocked/stubbed by callers.