javascript - 如何分别测试 ExpressJS 路由和 'controller'

标签 javascript node.js unit-testing asynchronous express

我有一个 Express 路由定义如下(app 是我的 Express 应用程序):

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

在那个“ 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();
        }
      });
  });
}

这里,ExperimentSchema 是一个 Mongoose 模型。由于 Controller 方法访问数据库,我在测试中传递了一个回调,这样我就可以等待那些数据库调用返回并验证返回值。我这样做是基于 this question .

当我去测试路由时,我正在使用 supertest 进行测试,实际上是对路由进行 HTTP 调用。问题是,当我这样做时,Express 将 next 作为我的 random 方法的第三个参数注入(inject)。现在,callback() 别名 next(),一切都变得一团糟。如何分别测试我的路线和我的 Controller ?

最佳答案

测试此类 Controller 功能的最佳方法是模拟请求和响应数据并将其导出到像 mocha 这样的测试套件。尽管看起来您也需要模拟您的 Mongoose 模式。除非您想模拟这些功能的输入,否则没有简单的方法来测试这些组件。

关于javascript - 如何分别测试 ExpressJS 路由和 'controller',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25254357/

相关文章:

javascript - Leap Motion Controller 数据清理

javascript - 根据单选按钮值使用javascript(Node JS)将数据插入mysql(Sequelize)

javascript - 如何将 Node mysql 查询存储在变量中?

java - 有没有办法验证在使用 JUnit 时是否在测试方法中调用了 try/catch 指令的 Catch 部分?

javascript - 确定 char 是否在正则表达式中

javascript - 如何使用 Javascript 根据 HTML 中的输入文本字段更改文本元素?

javascript - 无法设置 Node 和express来提供文件

xcode - Xcode 12 中新的多平台模板的共享单元测试

python - 在 python 中,如何运行一个在我向其发送 Ctrl+D 之前不返回的命令行程序

javascript - 单选按钮不会以 html 形式显示