【问题标题】:Is there a way to test error handling in ExpressJS with Mocha when using a custom error handler?使用自定义错误处理程序时,有没有办法使用 Mocha 测试 ExpressJS 中的错误处理?
【发布时间】:2019-11-19 11:42:39
【问题描述】:

测试

    it('should fail trying to GET bookmarks with false user id',async () => {
      try {
        const response = await request(app)
          .get(baseApiUrlUnderTest + 'false_user_id/bookmarks')
          .set('Authorization', bearerToken);
      } catch (e) {
        console.log(e); //it doesn't reach this point
        expect(e.httpStatus).to.equal(HttpStatus.UNAUTHORIZED);
      }
    });

被测方法的相关部分:

/* GET bookmark of user */
personalBookmarksRouter.get('/', keycloak.protect(), wrapAsync(async (request, response) => {

  userIdTokenValidator.validateUserIdInToken(request);
 ...
}));

wrapAsync 确保将错误传递给自定义错误处理程序:

let wrapAsync = function (fn) {
  return function(req, res, next) {
    // Make sure to `.catch()` any errors and pass them along to the `next()`
    // middleware in the chain, in this case the error handler.
    fn(req, res, next).catch(next);
  };
}

导致被测方法抛出异常的validateUserIdInToken方法:

const AppError = require('../models/error');
const HttpStatus = require('http-status-codes');

let validateUserIdInToken = function (request) {
  const userId = request.kauth.grant.access_token.content.sub;
  if ( userId !== request.params.userId ) {
    throw new AppError(HttpStatus.UNAUTHORIZED, 'Unauthorized', ['the userId does not match the subject in the access token']);
  }
}

module.exports.validateUserIdInToken = validateUserIdInToken;

以及根中间件中的自定义错误处理程序:

app.use(function(err, req, res, next) {
  if (res.headersSent) {
    return next(err)
  }
  if(err instanceof AppError) { //execution lands here as expected and the test stops...
    res.status(err.httpStatus);
    return res.send(err);
  } else {
    res.status(err.status || HttpStatus.INTERNAL_SERVER_ERROR);
    res.send({
      message: err.message,
      error: {}
    });
  }

});

【问题讨论】:

  • 当你说,在你的测试中“它没有达到这一点”,你仍然得到response吗?
  • @laggingreflex 你是对的,我没想到要检查...自定义错误处理程序发送回“有效”响应以及预期的错误消息

标签: node.js express testing mocha.js integration-testing


【解决方案1】:

我认为您可能不正确地处理此问题。无效的身份验证不应在应用程序中引发错误 - 这实际上不是错误,而是验证问题。

如果身份验证失败,只需将相关的 http 错误代码 - 401 发送回客户端即可。

res.send(HttpStatus.UNAUTHORIZED, 'a message if you want'); // 401

在您的路由处理程序中:

personalBookmarksRouter.get('/', keycloak.protect(), wrapAsync(async (request, response) => {
  const userId = request.kauth.grant.access_token.content.sub;
  if ( userId !== request.params.userId ) {
     return response.send(HttpStatus.UNAUTHORIZED);
  }

 ...
}));

在您的测试中,检查状态 401:

chai.request(server)
    .get('/false_user_id/bookmarks')
    .end((err, result) => {
        if (err) {
            return callback(err);
        }

        result.should.have.status(401);
    });

【讨论】:

  • 这实际上正是代码现在的样子 -github.com/CodepediaOrg/bookmarks.dev-api/blob/…,但我想将验证“错误”等集中在一个中心位置...
  • 现在我有点烦恼这是否是一件好事(另见 - stackoverflow.com/questions/1504302/…)...@laggingreflex 指出我在这个追求中缺少什么
  • 这样说,如果你让用户提交一些需要验证的表单数据,如果字段不够长,会抛出异常吗?希望不会。您在这个问题中提出的问题不是catching 我们在答案中解决的客户端错误。我简要查看了那个 repo,如果找不到数据,我真的不建议返回 404 错误。提出一个关于从 API 返回错误的最佳实践的新问题,我们可以在那里解决一些想法。
  • 我完全明白你的意思,一个很大的优势是整合验证违规并发回。至于在这种情况下的 auth 部分,如果发生这种情况,它确实是“例外”......在这种情况下,有两种方法可以结束(api客户端将得到相同的响应)。它在后端代码中的处理方式(可读性、性能)对我很重要。
  • 您现在正在讨论一个更大的架构决策,该决策比您的问题更广泛,该问题与您的客户端请求未捕获从 API 返回的错误有关:console.log(e); //it doesn't reach this point。请关闭问题/接受解释问题的答案。开始一个新的架构问题,以便用户使用此问题以供将来参考。
【解决方案2】:

感谢@laggingreflex 的评论,我错过了调试响应实际上返回的预期状态和错误消息

调整后的测试用例现在看起来像这样:

    it('should fail trying to GET bookmarks with false user id',async () => {
        const response = await request(app)
          .get(baseApiUrlUnderTest + 'false_user_id/bookmarks')
          .set('Authorization', bearerToken);

        expect(response.status).to.equal(HttpStatus.UNAUTHORIZED);
    });

【讨论】:

  • 上面已经明确指出了我的回答:result.should.have.status(401);
  • 对不起,也许问题不够清楚,但重点是如何抛出异常,使用自定义错误处理程序并测试 - 只有测试需要调整,其他一切都保持不变相同的。您的建议是使用不同的方法...
  • 您一直在尝试 catch 在服务器上抛出/返回客户端上的 ajax 调用时出现“try”语句中的错误。您的客户端测试代码永远不会起作用,我向您展示了您应该在 mocha 测试中测试状态:In your test, check the for status 401:。
  • 查看之前的测试与您在答案中建议的完全一样,它仍然存在于主分支 - github.com/CodepediaOrg/bookmarks.dev-api/blob/…。该代码也与您建议的相同。但是在@laggginreflex 指出这一点之前,我想重构并且不知道我在做什么错……
  • Can't comment on what was/was not in a repo where and not going to check,但你的第一个代码示例中显示的问题和sn-p突出了问题 - 你有同样的结论得出你自己的答案。您甚至说过“我错过了调试,响应实际上返回了预期的状态和错误消息”。非常奇怪的行为,但很高兴您已将其分类,并且您的代码百科一切顺利。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2020-10-27
  • 2017-12-18
  • 2011-10-02
  • 2019-05-31
  • 2015-02-01
  • 1970-01-01
相关资源
最近更新 更多