检查给定的中间件是否被使用 [英] Check if a given middleware is being used

查看:158
本文介绍了检查给定的中间件是否被使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了官方文档,但是我找不到如何检查是当前应用程序正在使用给定的中间件(即Morgan)。因为我的中间件配置取决于开发/生产情况,我想检查他们在我的摩卡测试中是否活跃。

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

推荐答案

Express不允许这样非常干净。

Express doesn't allow for this very cleanly.

最好的方法是查看 app._router.stack ,具体来说是函数引用,或者如果这是不可能的,函数的名称:

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.

(伪代码-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.

这篇关于检查给定的中间件是否被使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆