[英]Testing async waterfall with mocha seems to stall
I'm trying to add some mocha testing to a node module I have, but I'm new to it, and my lack of concreteness in terms of callbacks is hampering me. 我正在尝试向我拥有的节点模块中添加一些摩卡测试,但是我是新手,而我在回调方面缺乏具体性阻碍了我。 I have tried to pare things back to the most straightforward example, but it's still not working. 我试图将事情简化为最简单的示例,但是仍然无法正常工作。
So my main.js
is 所以我的main.js
是
var async = require('async');
var myObject = {};
myObject.test = function(params) {
async.waterfall([
async.apply(test, params)
],
function(err, result){
if (err) {
console.log('Error: ' + err);
} else {
if (result === 200) {
return result;
}
}
});
};
function test(params, callback) {
if(params) {
callback(null, 200);
}
}
module.exports = myObject;
Then my test file 然后我的测试文件
var assert = require("assert");
var myObject = require('./main');
describe('test', function(){
it("should return 200", function(done){
myObject.test({test: 'such test'}, function(err, res) {
if (err) return done(err);
assert.equal(res, 200);
done(res);
});
})
});
If I just run mocha
it times out so I'm suspicious about that! 如果我只是运行mocha
它就会超时,所以我对此表示怀疑! Trying mocha --timeout 15000
also just stalls. 尝试mocha --timeout 15000
也会停顿。 Any direction you can provide would be really appreciated! 您可以提供的任何方向将不胜感激!
I got this far using this answer but can't get any further. 我已经用这个答案走了很远,但无法继续。
OK, I think I sorted it, but would still appreciate some feedback to see if I'm approaching it correctly, rather than just managing to get my test to pass. 好的,我想我对它进行了排序,但是仍然希望获得一些反馈,以查看我是否正确地进行了测试,而不仅仅是设法使我的测试通过。
var async = require('async');
var myObject = {};
myObject.test = function(params, callback) {
async.waterfall([
async.apply(test, params)
],
function(err, result){
if (err) {
console.log('Error: ' + err);
} else {
if (result === 200) {
callback(result);
}
}
});
};
function test(params, callback) {
if(params) {
callback(null, 200);
}
}
module.exports = myObject;
and the test file is 测试文件是
var assert = require("assert"); var assert = require(“ assert”); var myObject = require('./main'); var myObject = require('./ main');
describe('test', function(){
it("should return 200", function(done){
myObject.test({test: 'such test'}, function(res) {
assert.equal(res, 200);
done();
});
})
});
You fixed your main issue but your code still is broken. 您已解决主要问题,但代码仍被破坏。 When you have an async method that takes a callback, you must always invoke the callback exactly once in all cases or your program's control flow will break. 当您有一个采用回调方法的异步方法时, 在任何情况下都必须始终仅一次调用该回调方法,否则程序的控制流将中断。 If you write an if/else
clause, both branches must invoke the callback function. 如果编写if/else
子句,则两个分支都必须调用回调函数。 Both of your if
statements above violate the callback contract. 上面的两个if
语句都违反了回调合同。 Check out understanding error-first-callbacks from The Node Way for a good explanation. 查看来自The Node Way的了解错误优先回调的详细说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.