【问题标题】:How do I import routes for testing with Supertest?如何导入路由以使用 Supertest 进行测试?
【发布时间】:2016-04-29 12:08:56
【问题描述】:

我有一个经过 Mocha 测试的应用程序,我能够使用我现在拥有的东西成功运行我的测试,但我在我的测试文件中明确设置了一个 GET 路由到 /api/v1。这是测试文件...

API.js:

var request = require('supertest');
var express = require('express');
var app = express();
var router = express.Router();

app.get('/api/v1', function (req, res, next) {
  res.json({
    "Hello": "World"
  });
});

describe('API', function () {
  it("Says 'Hello' is 'World'", function (done) {
    request(app)
      .get('/api/v1')
      .expect('Content-Type', /json/)
      .expect(200, {
        Hello: 'World'
      }, done);
  });
});

你注意到我在require() 语句之后怎么说app.get() 了吗?我不想在这里这样做。我希望能够从我的项目的routes 目录中导入我的路线。

我很难相信我应该在我的测试文件中复制所有这些路线。我想如何从routes 目录导入路由以用于此测试文件?

【问题讨论】:

    标签: node.js express mocha.js supertest


    【解决方案1】:

    不需要将路由导入到测试文件中。一旦在express.Router 对象上定义了路由,并且app 使用了路由器,则只需从主应用程序文件中导出app

    您将在单独的文件中定义路由并导出路由器。 routes.js

    var express = require('express');
    var router = express.Router();
    
    // Define routes
    router.get('/api/v1', function (req, res, next) {
      res.json({
        "Hello": "World"
      });
    });
    
    // Export the router. This will be used in the 'app.js' file.
    

    app.js

    //Import the router
    var router = require('./routes');
    
    // Use the router as middleware for the app. This enables the app to
    // respond to requests defined by the router.
    app.use('/', router);
    
    // Export the app object
    module.exports = app;
    

    app.spec.js

    // Import the app
    var app = require('./app');
    
    // Use the app object in your tests
    describe('API', function () {
      it("Says 'Hello' is 'World'", function (done) {
        request(app)
          .get('/api/v1')
          .expect('Content-Type', /json/)
          .expect(200, {
            Hello: 'World'
          }, done);
      });
    });
    

    express.Router 帮助组织您的路线。这个问题在这里得到了完美的回答:What is the difference between "express.Router" and routing using "app.get"?

    【讨论】:

    • 我的路线(在routes 目录中)附加到express.Router(),那么app.get()express.Router() 之间有什么区别,我怎样才能让这些路线脱离express.Router() ?
    • 感谢您的澄清。我会更新答案。
    • 基本上我使用的是var app = express() 而不是var app = require('../app')。谢谢你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多