使用Mocha / Chai测试NodeJS匿名回调代码

时间:2015-08-24 19:58:13

标签: node.js unit-testing mocha chai

我是单位测试的新手。我在Node.js工作,而且我正在使用async module。这是我正在使用的代码:

module.exports = {
    postYelp: function (cb, results) {
        if (results.findLocation) {
            results.client.post(['resources', 'Yelp'].join('/'), results.findLocation, function (err, data, ctx) {
                /* istanbul ignore next  */
                if (err) {
                    cb(err);
                } else {
                    console.log('data', data);
                    console.log('ctx', ctx.statusCode);
                    return cb(null, ctx.statusCode);
                }
            });
        }
        /* istanbul ignore next  */
        else cb(null);
    },
}

正如您所看到的,函数调用results.client.post中的第三个参数是一个匿名回调。

我想要此回调的测试覆盖率。如果我可以轻松地重构以使用与回调相同的代码创建命名函数并替换它,我可以单独测试它。但是,封闭函数(" postYelp")有自己的回调(" cb"),必须在匿名回调函数中使用。

如何对这个匿名功能代码进行单元测试?

1 个答案:

答案 0 :(得分:1)

好的,我明白了。我没有必要重构,只需找到一种方法将参数传递给匿名回调。这是代码:

    describe('when postYelp method is called', function() {
    it('should call the post method', function() {
        var cbspy = sinon.spy(cb);
        var post = sinon.stub(client, 'post');
        var results = {};
        results.client = {};
        results.client.post = post;
        results.findLocation = {'id': 'lyfe-kitchen-palo-alto'};
        post.callsArgWith(2, null, {'statusCode': 201}, {'statusCode': 201});
        helpers.postYelp(cbspy, results);
        assert(cbspy.called);
        client.post.restore();
    });
});

基本上我使用sinon来创建内部函数的存根(client.post)。我在测试文件中需要客户端和OUTER功能。这一行允许我将正确的参数提供给内部函数:

post.callsArgWith(2, null, {'statusCode': 201}, {'statusCode': 201});

“2”表示匿名回调是post方法的函数调用中的第3个参数。 “null”是“错误”参数,对象“{'statusCode':201}”实际上可能是任何值。