Check if a given middleware is being used

2019-02-26 00:20发布

问题:

I tried the official documentation but I could not find out how to check is a given middleware (i.e. morgan) is being used by the current application. Since my middleware configuration depends on development/production situation, I would like to check for them being active within my mocha tests

回答1:

Express doesn't allow for this very cleanly.

The best you can do is to look at app._router.stack, specifically at the function references, or if that's not possible, the name of the functions:

function middlewareExists(app, name) {
    return !!app._router.stack.filter(function (layer) { 
        return layer && layer.handle && layer.handle.name === name; 
    }).length;
}

So, I recommend a slightly different approach. If you can get a reference to the middleware function you expect your app to use, you can stub use and assert on what was passed.

(pseudo-code-ish)

// server.js 

helperModule.registerMiddleware(app, 'production');

// helperModule.js

var someMiddleware = require('./someMiddleware');

module.exports = exports = {
    registerMiddleware: function (app, env) {
        if (env === 'production')
            app.use(someMiddleware);
    }
};

// helperModule.test.js

var helperModule = require('./helperModule');
var someMiddleware = require('./someMiddleware');
var app = { use: sinon.stub() };

helperModule.registerMiddleware(app, 'production');
expect(app.use).to.have.been.calledWith(someMiddleware);

Hope that's somewhat illustrative. The point is to inject things so that you don't need to assert on the actual express app itself, you can just inject mock objects and do your assertions based on those.