[英]How to unit test express route that calls helper function from dependency?
[英]Dependency inject into Express route
我需要将我的db
对象注入到securityHandler
对象中,但我似乎无法弄清楚如何去做。
在securityHandler.authenticate
方法中,我想访问所有: db
、 request
和response
。
我试过这个:
app.post('/api/login', securityHandler.authenticate(request, response, db) );
和
SecurityHandler.prototype.authenticate = function authenticate(request, response, db) {};
编辑:
nane 建议将 db 对象传递给 SecurityHandler 的构造函数:
var security = new SecurityHandler(db);
SecurityHandler 本身看起来像这样:
function SecurityHandler(db) {
console.log(db); // Defined
this.db = db;
}
SecurityHandler.prototype.authenticate = function authenticate(request, response, next) {
console.log(this.db); // Undefined
};
db 对象现在存在于构造方法中,但由于某种原因在身份验证方法中无法访问。
securityHandler.authenticate(request, response, db)
将立即调用authenticate
,因为您会将authenticate
调用的结果作为回调传递给app.post('/api/login', /*...*/)
。
你需要这样做:
app.post('/api/login', function(request, response) {
securityHandler.authenticate(request, response, db);
});
您可以在 express.js 中编写自定义中间件,并在路由任何请求之前使用它。
有关自定义中间件的更多信息 - 您可以参考 - Express.js Middleware Demystified
现在在这个中间件中,您可以实现与身份验证相关的功能,该功能将在所有请求之前触发,您可以根据中间件本身的 request.url 操作代码。
希望这会帮助你。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.