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

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.

Leave a Comment