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

express, integration-testing, mocha.js, node.js, testing

Solution

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.

Problem

My application has several layers: middleware, controllers, managers. Controllers interface is identical to middlewares one: (req, res, next). So my question is: how can I test my controllers without starting the server and sending 'real' requests to localhost. What I want to do is to create request, response instances as nodejs does and then just call controllers method. Something like this: ``` var req = new Request() var res = new Response() var next = function(err) {console.log('lala')} controller.get_user(req, res, next) ``` Any advice is highly appreciated. Thanks! P.S. the reason why I want to do this is that at the end I would like to test whether the response object contains correct variables for the jade views.

Original source