Zborchik Chehow Zborchik Chehow - 3 months ago 23
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.

EDIT:

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.

Answer

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) {
        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")

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.

Comments