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

后端 未结 6 713
花落未央
花落未央 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:31

    Since JavaScript is a dynamically typed language you can create mock objects and passing them to your controllers as follow:

    var req = {};
    var res = {};
    var next = function(err) {console.log('lala')}
    controller.get_user(req, res, next)
    

    If your controller needs a particular piece of data or functionality from your request or response object you'll need to provide such data or functionality in your mocks. For example,

    var req = {};
    req.url = "http://google.com"; // fake the Url
    
    var res = {};
    res.write = function(chunk, encoding) { 
      // fake the write method 
    };
    
    var next = function(err) {console.log('lala')}
    controller.get_user(req, res, next)
    

提交回复
热议问题