简体   繁体   English

如何分别测试ExpressJS路由和“控制器”

[英]How to test an ExpressJS route and 'controller' separately

I have an Express route defined as follows (where app is my Express app): 我有一个Express路由定义如下(其中app是我的Express应用程序):

module.exports = function(app) {
  var controller = require('../../app/controllers/experiment-schema');
  app.route('/api/experiment-schemas/random').get(controller.random);
};

In that 'controller' file, I have this method: 在那个'controller'文件中,我有这个方法:

exports.random = function (req, res, callback) {

  ExperimentSchema.count({}, function (err, count) {

    var rand = Math.floor(Math.random() * count);

    ExperimentSchema.find({})
      .skip(rand)
      .limit(1)
      .populate('mediaPool', 'artist title label')
      .exec(function (err, schema) {

        res.json(200, schema);

        if (typeof callback === 'function') {
          callback();
        }
      });
  });
}

Here, ExperimentSchema is a Mongoose model. 这里, ExperimentSchema是一个Mongoose模型。 Since the controller method hits the database, I'm passing in a callback in my test so that I can wait for those database calls to return and verify the return value. 由于控制器方法命中数据库,我在测试中传入一个回调,以便我可以等待那些数据库调用返回并验证返回值。 I'm doing this based on this question . 我是基于这个问题做的。

When I go to test the route, I'm testing with supertest , actually making the HTTP call to the route. 当我去测试路由时,我正在测试supertest ,实际上是对路由进行HTTP调用。 The problem is that when I do this, Express is injecting next as the third argument to my random method. 问题是,当我这样做时,Express会将next作为random方法的第三个参数注入。 Now, callback() aliases next() , and everything goes haywire. 现在, callback()别名next() ,一切都变得混乱。 How can I test my route and my controller seperately? 如何单独测试我的路线和控制器?

The best way to test controller functions like that is to just mock the request and response data and export it to a test suite like mocha. 测试控制器函数的最佳方法是模拟请求和响应数据并将其导出到像mocha这样的测试套件。 Though it also seems like you will need to mock out your mongoose schema's as well. 虽然看起来你也需要嘲笑你的mongoose架构。 There is no easy way to test these components unless you want to mock the inputs for these functions. 除非您想模拟这些函数的输入,否则没有简单的方法来测试这些组件。

我通过重构路由来修复此问题,只期望默认参数reqres

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM