how to unit test contents of a callback function with sinon.js
Asked Answered
P

1

7

how does one test a code inside a callback function using sinon.js framework for mocking?

JSFiddle: http://jsfiddle.net/ruslans/CE5e2/

var service = function () {
    return {
        getData: function (callback) {
            return callback([1, 2, 3, 4, 5]);
        }
    }
};

var model = function (svc) {
    return {
        data: [],
        init: function () {
            var self = this;
            svc.getData(function (serviceData) {
                self.data = serviceData; // *** test this line ***
            });
        }
    }
};

I use mocha tests with chai but am familiar with qUnit, so any of these tests would be accepted.

Panzer answered 4/2, 2014 at 14:52 Comment(0)
P
11

callsArgWith(0, dataMock) does the trick: http://jsfiddle.net/ruslans/3UtdF/

var target,
    serviceStub,
    dataMock = [0];

module("model tests", {
    setup: function () {
        serviceStub = new service();
        sinon.stub(serviceStub);
        serviceStub.getData.callsArgWith(0, dataMock);

        target = new model(serviceStub);
    },
    teardown: function () {
        serviceStub.getData.restore();
    }
});

test("data is populated after service.getData callback", function () {
    target.init();
    equal(target.data, dataMock);
});
Panzer answered 4/2, 2014 at 17:18 Comment(1)
In the case of just one callback, it is also possible to apply .yields( dataMock ) Sinon.js docs. Cheers!Muskellunge

© 2022 - 2024 — McMap. All rights reserved.