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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21555718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:09:54  来源:igfitidea点击:

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

javascriptunit-testingmochaqunitsinon

提问by Грозный

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

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

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

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.

我使用带有 chai 的 mocha 测试但熟悉 qUnit,因此任何这些测试都将被接受。

回答by Грозный

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

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);
});