这是我在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() { ... });