如何使用node-mocks-http测试异步?例如:我在我的快递路由器中有这个,可以通过GET / category / list
到达var getData = function (req, res) {
Category.find({}, function (err, docs) {
if (!err) {
res.json(200, { categories: docs });
} else {
res.json(500, { message: err });
}
});
};
并在测试中
var request = httpMocks.createRequest({
method: 'GET',
url: '/category/list',
body: {}
});
var response = httpMocks.createResponse();
getData(request, response);
console.log(response._getData());
test.done();
但是响应不包含json(响应在几秒钟之后回来)。我该怎么测试呢?非常感谢任何帮助。
答案 0 :(得分:1)
您可以将回调参数传递给getData
函数,该函数在Mongoose返回数据时执行。
var getData = function (req, res, cb) {
Category.find({}, function (err, docs) {
if (!err) {
res.json(200, { categories: docs });
} else {
res.json(500, { message: err });
}
cb();
});
};
然后再做
var request = httpMocks.createRequest({
method: 'GET',
url: '/category/list',
body: {}
});
var response = httpMocks.createResponse();
getData(request, response, function() {
console.log(response._getData());
test.done();
});