2

这是我创建的一个小型中间件,用于在我的 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(); };
    }
}

我对它的外观不满意。有没有更优雅的方式来实现这一点?

4

1 回答 1

1

我认为您对外观不满意是正确的。我认为您真正想要做的是从测试代码中模拟您的身份验证,而不是在您的实际应用程序代码中。一种方法是通过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() { ... });
于 2016-12-19T00:22:39.673 回答