How to mock request and response in nodejs to test middleware/controllers?

后端 未结 6 712
花落未央
花落未央 2021-02-01 14:37

My application has several layers: middleware, controllers, managers. Controllers interface is identical to middlewares one: (req, res, next).

So my question is: how ca

6条回答
  •  佛祖请我去吃肉
    2021-02-01 15:21

    If you want to use the real req and res objects, you have to send real requests to the server. However this is much easier than you might think. There are a lot of examples at the express github repo. The following shows the tests for req.route

    var express = require('../')
      , request = require('./support/http');
    
    describe('req', function(){
      describe('.route', function(){
        it('should be the executed Route', function(done){
          var app = express();
    
          app.get('/user/:id/edit', function(req, res){
    
            // test your controllers with req,res here (like below)
    
            req.route.method.should.equal('get');
            req.route.path.should.equal('/user/:id/edit');
            res.end();
          });
    
          request(app)
          .get('/user/12/edit')
          .expect(200, done);
        })
      })
    })
    

提交回复
热议问题