我是新来的在node.js中测试,我想模拟一个特定的函数调用返回的过程,看起来像下面。node.js中的模拟函数返回测试
doSomething(function(err, res){
callAnotherOne(res, function(err, result){
getDataFromDB(result, function(err, docs){
//some logic over the docs here
})
})
})
,我想嘲笑的功能为getDataFromDB()和专门的文件(使用MongoDB的),它返回。 我怎么能用摩卡做这样的事情?
部分代码,从逻辑条之间,如下:
filterTweets(item, input, function(err, item) {
//Some filtering and logging here
db.getTwitterReplies(item, function(err, result) {
if(err) {
return callback('Failed to retrieve tweet replies');
}
//Do some work here on the item using the result (tweet replies)
/***** Here I want to test that the result is the expected ****/
db.storeTweets(item function (err, result){
//error checks, logging
callback();
});
});
});
基于在twitter回复(函数调用“getTwitterReplies”)的量,我将相应地修改我的对象(没不包括该代码)。我想看看如果根据不同的回复结果,我的对象按预期构建。
p.s.我也在一些搜索后检查了sinon.js,并设法模拟回调(通过在我的项目之外编写一些测试代码)而不是返回嵌套函数调用的回调。
导入的,我不能真正想到这个解决方案,而没有看到它是如何绑在一起的一个例子。 – James 2014-09-22 10:59:59
我编辑我的答案,通过添加我想模拟的代码。 – 2014-09-22 11:45:28
require()的范围可以提供一种方法来在sinon.js的测试中进行简单的依赖注入,而不需要引入大量额外的函数参数。我将根据这些方面进行更广泛的回答。 – LrdCasimir 2014-09-23 00:35:51