摩卡testing在失败时执行两次callback

我有一个简单的Mongoose模式,我正在用Mochatesting; 当我用'成功'callback运行testing它正常执行,但是当最后一个testing执行失败,似乎再次运行testing(我得到两个结论,一个填充错误对象和第二个返回null在错误对象)。运行下面的两个testing会导致以下输出:

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 

这个testing重复

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

这个testing工作

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

每当你这样做,添加一个return; 避免两次调用donecallback。 这是摩卡,但也为一般node.jscallback处理。

  if (err) { console.log("Unable to create cabinet"); done(err); return; } 

内阁架构中的同样的问题:

 if (err) cb(err,null); 

这需要一个回报,或者它会调用callback两次,并导致混乱(也深深地知道node.js博客作为“释放Zalgo”的一种味道)。