【问题标题】:Use Mocha/Chai to test NodeJS anonymous callback code使用 Mocha/Chai 测试 NodeJS 匿名回调代码
【发布时间】:2015-11-18 08:58:10
【问题描述】:

我是单元测试的新手。我在 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”),必须在匿名回调函数中使用。

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

【问题讨论】:

    标签: node.js unit-testing mocha.js chai


    【解决方案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 方法的函数调用中的第三个参数。 “null”是“err”参数,对象“{'statusCode': 201}”实际上可以是任何值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多