Zborchik Chehow Zborchik Chehow - 1 year ago 111
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download