运行testing时如何优雅地跳过express-jwt中间件?

这是我创build的一个小型中间件,用于在我的nodejs应用程序testing期间跳过身份validation:

authentication(auth) { if (process.env.NODE_ENV !== 'test') { return jwt({ secret: new Buffer(auth.secret, 'base64'), audience: auth.clientId }); } else { return (req, res, next) => { next(); }; } } 

我对它的样子并不满意。 有没有更完美的方式来完成这个?

我觉得你是对的,看起来很不高兴。 我认为你真正想要做的就是从testing代码中嘲笑你的authentication,而不是在实际的应用代码中。 一个办法是通过proxyquire来做到这一点。

然后,如果app.js需要通过var authentication = require('./lib/authentication')那么一个非常简单的testing可能看起来像这样

 var proxyquire = require('proxyquire'); var app = proxyquire('./app.js', { './lib/authentication': function() { // your "test" implementation of authentication goes here // this function replaces anywhere ./app.js requires authentication } }); it('does stuff', function() { ... });