使用Mocha / Chai来testingNodeJS的匿名callback代码

我是unit testing的新手。 我正在使用Node.js,我正在使用asynchronous模块 。 这是我正在使用的代码:

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中的第三个参数是一个匿名callback函数。

我想要testing这个callback的覆盖范围。 如果我可以轻松地使用与callback相同的代码重新创build一个命名的函数并replace它,我可以单独testing它。 但是,封闭函数(“postYelp”)有自己的callback(“cb”),必须在匿名callback函数中使用。

我怎样才能unit testing这个匿名函数代码?

好,我明白了。 我不必重构,只需要find一种方法将parameter passing给匿名callback。 代码如下:

  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创build了一个内部函数(client.post)的存根。 我在我的testing文件中需要客户端和OUTERfunction。 这一行允许我将正确的参数提供给内部函数:

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

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