2015-08-24 66 views
2

我是单元测试的新手。我在Node.js中工作,我正在使用async module。这里是我正在使用的代码:使用Mocha/Chai来测试NodeJS的匿名回调代码

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

好的我想通了。我不必重构,只需找到一种方法将参数传递给匿名回调。下面的代码:

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

基本上我使用兴农创建内部函数(client.post)的残余部分。我在我的测试文件中需要客户端和OUTER功能。此行让我正确的参数输送给内部函数:

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

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

相关问题