【问题标题】:How can i test async functions using express, mongoose and nodeunit?如何使用 express、mongoose 和 nodeunit 测试异步函数?
【发布时间】:2014-12-31 05:14:25
【问题描述】:

我如何使用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(响应会在几秒钟后返回)。我该如何测试呢?非常感谢任何帮助。

【问题讨论】:

    标签: javascript node.js unit-testing express mongoose


    【解决方案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();
    });
    

    【讨论】:

    • 谢谢。除了添加回调之外的任何其他方式,因为我现在有很多代码正在编写测试,所以我想在测试中添加一些东西而不是更改代码。
    • 不是我所知道的,虽然你会开始注意到你几乎每个函数都需要回调,所以向现有函数添加回调没有任何问题.
    • 好的。最后一个问题 - 我的 app.js 在 app.js app.use('/category/list', categories.getData); 中有上述功能的路由并在 routes/categories.js var getData = function (req, res) { .... } 现在如果我添加回调,express 将能够路由它?
    猜你喜欢
    • 2015-04-25
    • 2013-08-02
    • 2011-11-03
    • 1970-01-01
    • 2015-05-11
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多