Check if a given middleware is being used

前端 未结 1 1230
小鲜肉
小鲜肉 2021-01-21 08:52

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 config

1条回答
  •  南方客
    南方客 (楼主)
    2021-01-21 09:40

    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.

    0 讨论(0)
提交回复
热议问题