我尝试用mocha,supertest和sinon测试这个快速路线。测试无法通过promise,它在User.find回调函数中第一次mongoose调用后停止,并带有待处理的错误消息:
错误:超出2000毫秒的超时。确保在此测试中调用done()回调。
我在回调中调用done()但没有...
module.exports = function(app, User) {
app.route('/appointments')
.post(function(req,res){
User.find({'department': req.body.department}, function(err, workers){
return workers._id;
}).then(function(allWorkers){
var deferred = Q.defer();
function sortWorkers(worker){
return Appointments.find({worker: worker._id, start: req.body.date});
};
Q.all(_.map(allWorkers, sortWorkers)).done(function (val) {
deferred.resolve(val);
});
return deferred.promise;
}).then(function(workers){
console.log(workers);
})
.catch(function(error) {
console.log(error);
})
.done();
})
};
这是我的开始测试:
it("should save a user and not save the same", function(done){
var appointments = new Appointments({title: 'okok',worker: '580359c86f7159e767db16a9',start:'2015-04-08T02:50:04.252Z' ,department: 95});
console.log('appointments',appointments);
request(app)
.post("/appointments")
.send(appointments)
.expect(200)
.end(function(err,res){
console.log('ok',res);
done();
});
});
答案 0 :(得分:0)
首先,您不需要在done
承诺致电User.find
此外,您的app.route('/appointments').post
永远不会返回任何内容作为回复,请尝试添加
res.end();
您承诺的console.log
和.then
.catch
。您也可以使用HTTP状态代码,例如
...
}).then(function(workers){
res.status(200).end();
})
.catch(function(error) {
res.status(500).end();
})
这将确保在您的测试中调用.end(function(err,res){ ... })
并调用正确的done
函数。
答案 1 :(得分:0)
您应该始终从单元测试中回复承诺。 您只需在请求(app)之前添加 return :
return request(app)
.post("/appointments")
. . .
.then(() => {
expect(<your actual value>).to.equal(<expected value>)
})
答案 2 :(得分:0)
我找到了解决方案: 在我的一些.then函数没有条件,并返回什么,如果工作数组例如为空,这就是为什么我的测试返回超过2000毫秒的超时。
我补充说:
User.find({'department': req.body.department}, function(err, workers){
if(workers.length == 0){
res.status(500).json({ message: "Nobody in this department" });
}
return workers;
})...