Chris
Chris

Reputation: 4225

How to test nested callbacks with Mocha/Sinon?

What is the/one correct way to test this piece of JavaScript code using, e.g, Mocha/Sinon:

var App = function(endPoint, successCallback) {
    var channel = new WebSocket(endPoint);
    channel.onopen = function(ev) {
        successCallback();
    };
};

I'm thinking of something like this:

describe('App', function() {
    it('test should create instance and call success', function(done) {
        var app = new App('ws://foo.bar:123/', done);
        var stub = sinon.stub(app, 'channel');
        stub.yield('onopen');
    });
});

Apparently, that does not work as channel is not accessible from outside the constructor. How would you test this?

Upvotes: 1

Views: 677

Answers (1)

T. Junghans
T. Junghans

Reputation: 11683

Why not create a factory for Websocket such as:

var myApp = {
    createWebsocket: function () {
        return new Websocket;
    }
};

This would make spying on the myApp.createWebsocket return value channel very easy:

sinon.spy(myApp, 'createWebsocket);
var channel = myApp.createWebsocket.firstCall.returnValue;
var stub = sinon.stub(channel, 'onopen');
stub.yield('onopen');

// Clean up
myApp.createWebsocket.restore();

Upvotes: 1

Related Questions