我有一个简单的Mongoose架构,我正在使用Mocha进行测试;当我使用'success'回调运行测试时它会正常执行,但是当最后一个测试执行时它失败并且似乎再次运行测试(我得到两个结论,一个用于填充错误对象,另一个用于返回null)错误对象。)运行以下两个测试会产生以下输出:
Cabinet:
â should return all authorized
â should return not authorized <-- it succeeds the first time?
1) should return not authorized
2 passing (42ms)
1 failing <--- what? there are only two tests
1) Cabinet: should return not authorized :
Uncaught AssertionError: expected null to exist <--- see test
此测试重复
it("should return not authorized error ", function(done){
var newCabinet = {
name: "A new cabinet",
description: "Some remote cabinet",
authorizedBorrowers : ["imatest","imanothertest"],
cabinetInventory : []
};
Cabinet.newCabinet(newCabinet, function(err, cabinet){
if (err) {
console.log("Unable to create cabinet");
done(err);
}
Cabinet.isAuthorizedBorrower(cabinet._id, "bob", function(cberr, borrower){
should.exist(cberr); <-- 'expected null to exist' points here
done();
});
});
});
本测试工作
it("should not return unauthorized error ", function(done){
var newCabinet = {
name: "A new cabinet",
description: "Some remote cabinet",
authorizedBorrowers : ["imatest","imanothertest"],
cabinetInventory : []
};
Cabinet.newCabinet(newCabinet, function(err, cabinet){
if (err) {
console.log("Unable to create cabinet");
done(err);
}
//console.log("ID " + cabinet._id)
Cabinet.isAuthorizedBorrower(cabinet._id, "imatest", function(cberr, borrower){
should.not.exist(cberr);
done();
});
});
});
架构
var cabinetSchema = new Schema({
name: String,
description: String,
thumbnail : Buffer,
authorizedBorrowers : [],
defaultCheckout : {type : Number, default: 0} // default checkout mins = no time
});
var hasBorrower = function(cabinet, borrower){
if (cabinet===null) return false;
if (cabinet.authorizedBorrowers.length === 0) return false;
return (cabinet.authorizedBorrowers.indexOf(borrower) >= 0)
}
cabinetSchema.statics.isAuthorizedBorrower = function(cabinet_id, borrowername, cb ){
this.findOne({_id: cabinet_id}, function(err, cabinet){
if (err) cb(err,null);
if (!hasBorrower(cabinet, borrowername)) cb(new Error(errorMsgs.borrowerNotAuthorized),null);
cb(null,borrowername);
});
};
答案 0 :(得分:2)
每当您执行此操作时,请添加return;
以避免两次调用done
回调。这适用于mocha,但也适用于一般node.js回调处理。
if (err) {
console.log("Unable to create cabinet");
done(err);
return;
}
您的Cabinet架构中存在同样的问题:
if (err) cb(err,null);
需要返回或者它会调用两次回调并导致混乱(在node.js博客圈中也被亲切地称为“释放Zalgo”的一种风格)。