在运行测试时,如何优雅地跳过Express-JWT中间件



这是我在nodejs应用程序测试期间跳过身份验证的小中间件:

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(); };
    }
}

我对它的外观不满意。是否有更优雅的方法来实现这一目标?

我认为您对外观不满意是正确的。我认为您真正想做的是从测试代码而不是在实际应用程序代码内嘲笑您的身份验证。一种方法是通过ProxyQuire。

然后,如果app.js需要通过 var authentication = require('./lib/authentication')

进行身份验证,则非常简单的测试可能看起来像这样。
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() { ... });

最新更新