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

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

    There's a semi decent implementation at node-mocks-http

    Require it:

    var mocks = require('node-mocks-http');
    

    you can then compose req and response objects:

    req = mocks.createRequest();
    res = mocks.createResponse();
    

    You can then test your controller directly:

    var demoController = require('demoController');
    demoController.login(req, res);
    
    assert.equal(res.json, {})
    

    caveat

    There is at time of writing an issue in this implementation to do with the event emitter not being fired.

提交回复
热议问题