Skip to content

Instantly share code, notes, and snippets.

@jmervine
Created March 10, 2014 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmervine/9474549 to your computer and use it in GitHub Desktop.
Save jmervine/9474549 to your computer and use it in GitHub Desktop.

Mocking Middleware in Node.js is Easy

Mocking [Connect] or [Express] middleware in Node.js is easy. Simple create your request and response objects and use the next function as the harness to tests.

I'm going to assume [Tape] for this example, but this is easily ported to [Mocha], [nodeunit] or any other test harness of your choosing.

// file: simple_middleware.js
module.exports = function(request, response, next) {
    response.foo = 'foo';
    next();
};
// file: simple_middleware_test.js
var tape = require('tape');
var middleware = require('my_middleware');

tape('simplest middleware test possible', function(test) {
    var request, response;
    request = response = {};
    middleware(request, response, function() {
        test.equal(response.foo, 'foo');
        test.end();
    });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment