【发布时间】:2019-06-27 13:22:43
【问题描述】:
我正在编写一个 ExpressJS 中间件,它稍微修改请求对象并检查用户是否有权访问该特定页面。我对它进行单元测试有问题。我已经为每个方法编写了单独的测试,除了一个:handler。如何测试handler 功能?我应该测试它吗?或者我应该用istanbul ignore next 忽略它,因为我已经涵盖了所有其他功能?或者也许我应该以某种方式重写我的handler 函数以使其可测试?
class Example {
constructor(request, response, next, userAccountService) {
this.req = request;
this.res = response;
this.next = next;
this.userAccountService = userAccountService;
}
removeTokenFromQuery() {
delete this.req.query.token;
}
isValidRequest() {
if (!this.req.secure) {
return false;
}
if (typeof this.req.query.token !== 'undefined') {
return false;
}
if (typeof this.req.query.unsupportedQueryParam !== 'undefined') {
return false;
}
return true;
}
isPageAccessibleForUser() {
return this.userAccountService.hasAccess('example');
}
async handler() {
this.removeTokenFromQuery();
if (!this.isValidRequest()) {
throw new Error('Invalid request');
}
if (!this.isPageAccessibleForUser()) {
this.res.statusCode(500);
this.res.end();
return;
}
this.next();
}
}
然后它被称为 Express 中间件:
this.app.use((res, req, next) => {
const exampleObj = new Example(res, req, next, userAccServ);
exampleObj.handler();
});
【问题讨论】:
标签: javascript unit-testing express mocha.js