【问题标题】:Add application-level express middleware in test在测试中添加应用级 express 中间件
【发布时间】:2019-08-13 13:27:46
【问题描述】:

演示:https://codesandbox.io/s/mocha-chai-http-tests-o31ov 我尝试像这样在测试阶段添加应用程序级中间件

it("GET/ Get custom response", function(done) {
    app.use("/custom", (req, res, next) => {
      res.status(200).send({
        customMessage: "custom",
        customData: {
          version: "v1"
        }
      });
    });

    chai
      .request(app)
      .get("/custom")
      .end((err, res) => {
        console.log("CUSTOM", res.body);
        res.should.have.status(200);
        res.body.should.be.a("object");
        res.body.should.have.property("customMessage");
        res.body.should.have.property("customData");
        done();
      });
  });

但测试没有使用它,它属于根目录下的 404-middleware。如何在测试中使用自定义路由?

【问题讨论】:

    标签: node.js express mocha.js tdd chai


    【解决方案1】:

    中间件加载的顺序很重要:先加载的中间件函数也会先执行。

    当您尝试访问 /custom 路由时出现 404 的原因是您在 404 错误处理程序中间件之后加载此路由。我们需要在 404 错误处理程序中间件之前保持 /custom 路由负载。这是一个解决方案:

    app.js:

    const createError = require('http-errors');
    const express = require('express');
    
    function createApp(customRoute) {
      const app = express();
    
      app.use(express.json());
      app.use(express.urlencoded({ extended: false }));
      app.use('/api', function(req, res) {
        res.status(200).send({
          message: 'API',
          data: {
            version: 'v1',
          },
        });
      });
      if (customRoute) {
        app.use(customRoute.route, customRoute.controller);
      }
    
      // catch 404 and forward to error handler
      app.use(function(req, res, next) {
        next(createError(404));
      });
    
      // error handler
      app.use(function(err, req, res, next) {
        res.status(err.status).send({
          status: err.status,
          error: err,
        });
      });
    
      return app;
    }
    
    module.exports = createApp;
    

    app.test.js:

    const chai = require('chai');
    const chaiHttp = require('chai-http');
    const createApp = require('./app');
    
    chai.use(chaiHttp);
    chai.should();
    
    describe('API test', function() {
      it('GET/ Get root response', function(done) {
        const app = createApp();
        chai
          .request(app)
          .get('/api')
          .end((err, res) => {
            console.log('NORMAL', res.body);
            res.should.have.status(200);
            res.body.should.be.a('object');
            res.body.should.have.property('message');
            res.body.should.have.property('data');
            done();
          });
      });
    
      it('GET/ Get custom response', function(done) {
        const customRoute = {
          route: '/custom',
          controller: (req, res, next) => {
            res.status(200).send({
              customMessage: 'custom',
              customData: {
                version: 'v1',
              },
            });
          },
        };
        const app = createApp(customRoute);
    
        chai
          .request(app)
          .get('/custom')
          .end((err, res) => {
            console.log('CUSTOM', res.body);
            res.should.have.status(200);
            res.body.should.be.a('object');
            res.body.should.have.property('customMessage');
            res.body.should.have.property('customData');
            done();
          });
      });
    });
    

    单元测试结果:

      API test
    NORMAL { message: 'API', data: { version: 'v1' } }
        ✓ GET/ Get root response (44ms)
    CUSTOM { customMessage: 'custom', customData: { version: 'v1' } }
        ✓ GET/ Get custom response
    
    
      2 passing (62ms)
    

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 2013-08-22
      • 2020-05-17
      • 1970-01-01
      • 2017-03-30
      相关资源
      最近更新 更多