【问题标题】:Assert exception details with JestJS使用 JestJS 断言异常细节
【发布时间】:2020-03-13 07:44:27
【问题描述】:

问题

我设置了以下 Jest 测试以确保抛出异常:

it('can not rollback a step', async () => {
  await expect(app.service('rides').patch(ride._id, {
    currentStep: 1,
  })).rejects.toThrow(BadRequest);
});

如何断言异常内容?

示例

考虑到这个 BadRequest 错误:

    BadRequest {
      type: 'FeathersError',
      name: 'BadRequest',
      message: 'invalid data',
      code: 400,
      className: 'bad-request',
      data: {},
      errors: [
        {
          message: 'currentStep must be greater than 1',
          path: [Array],
          type: 'array.min',
          context: [Object]
        }
      ],

我想检查errors[0].message 的内容,不管错误对象的其余部分。

【问题讨论】:

    标签: javascript typescript exception jestjs


    【解决方案1】:

    catch 然后分析。不要忘记jest.assertions() 以确保代码真正抛出。

    jest.assertions(1);
    try {
      await app.service('rides').patch(ride._id, {
        currentStep: 1,
      });
    } catch(e) {
      expect(e.errors[0].message).toEqual('abc');
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 1970-01-01
      • 2018-09-26
      • 2020-10-25
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2021-04-06
      相关资源
      最近更新 更多