【发布时间】:2015-05-11 19:36:14
【问题描述】:
我正在尝试使用 Mocha 和 Chai 测试我的 REST API 端点处理程序,该应用程序是使用 Express 和 Mongoose 构建的。我的处理程序主要是以下形式:
var handler = function (req, res, next) {
// Process the request, prepare the variables
// Call a Mongoose function
Model.operation({'search': 'items'}, function(err, results) {
// Process the results, send call next(err) if necessary
// Return the object or objects
return res.send(results)
}
}
例如:
auth.getUser = function (req, res, next) {
// Find the requested user
User.findById(req.params.id, function (err, user) {
// If there is an error, cascade down
if (err) {
return next(err);
}
// If the user was not found, return 404
else if (!user) {
return res.status(404).send('The user could not be found');
}
// If the user was found
else {
// Remove the password
user = user.toObject();
delete user.password;
// If the user is not the authenticated user, remove the email
if (!(req.isAuthenticated() && (req.user.username === user.username))) {
delete user.email;
}
// Return the user
return res.send(user);
}
});
};
问题在于函数在调用 Mongoose 方法和测试用例时返回,如下所示:
it('Should create a user', function () {
auth.createUser(request, response);
var data = JSON.parse(response._getData());
data.username.should.equal('some_user');
});
在执行任何操作之前,永远不要通过函数返回。 Mongoose 使用 Mockgoose 模拟,请求和响应对象使用 Express-Mocks-HTTP 模拟。
虽然使用 superagent 和其他请求库相当普遍,但我更愿意单独测试这些功能,而不是测试整个框架。
有没有办法让测试在评估 should 语句之前等待而不更改我正在测试的代码以返回承诺?
【问题讨论】:
标签: node.js testing express mongoose mocha.js