如何测试异步模块中是否按预期调用回调?

时间:2016-04-25 16:45:27

标签: node.js asynchronous mocha sinon chai

在下面的代码中,在异步模块的帮助下,两个函数同时运行。一旦获得两个函数的结果,就会调用最终函数dosomething3()。我如何测试是否调用了正确的回调?

async.parallel([
    function(cb) {
        doSomething1(function(err, result) {
            if (err) return cb(err);    // WANT TO TEST
            cb(null, result);    //WANT TO TEST
        });
    },

    function(cb) {
        doSomething2(function(err, result) {
            if (err) return cb(err);    // WANT TO TEST
            cb(null, result);    //WANT TO TEST
        });
    }

], function(err, data) {
    if (err) return handleError(err);    //WANT TO TEST
    var result1 = data[0];
    var result2 = data[1];

    dosomething3(result1, result2, function(err) {
        if (err) return handleError(err);
        process.exit(0);
    })
});

1 个答案:

答案 0 :(得分:0)

如果你想编写单元测试,你必须为函数doSomething1,doSomething2,dosomething3,handleError编写函数。因此,根据测试用例,您可以设置(或不设置)这些函数的错误。

例如,doSomething1()的模拟看起来像这样(它只是想法,sinon提供了测试函数调用的工具。请参阅here ):

// global variables that are used to controll data passed in callback of doSomething1()
var doSomething1Error = null,
    doSomething1result = [],
    doSomething1CallCount = 0;
// the mock 
function doSomething1(cb) {
  doSomething1CallCount++;
  cb(doSomething1Error, doSomething1result);
}

然后,您的测试用例将如下所示

describe('doSomething1 ', function() {
  beforeEach(function(done) {
    // reset global vars used by mock
    doSomething1Error = null;
    doSomething1result = [];
    doSomething1CallCount = 0;
  });

  it('is called once with error', function() {
    doSomething1Error = 'User does not exist';
    // call you code under test (async.parallel([.....]))

    // check that doSomething1CallCount == 1
    // check that mock for handleError was called with 'User does not exist' error
  });

})