如何使用sinon.js对回调函数的内容进行单元测试

Гро*_*ный 7 javascript unit-testing qunit mocha.js sinon

如何使用sinon.js框架进行模拟来测试回调函数内的代码?

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 ***
            });
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

我使用chai的mocha测试但是熟悉qUnit,因此任何这些测试都会被接受.

Гро*_*ный 11

callsArgWith(0, dataMock)诀窍: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);
});
Run Code Online (Sandbox Code Playgroud)