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.