小编dec*_*ijo的帖子

在玩笑中编写单元测试时预期会出现特定错误

我使用 nestjs (6.5.0) 和 jest (24.8) 并有一个抛出错误的方法:

  public async doSomething(): Promise<{ data: string, error?: string }> {
    throw new BadRequestException({ data: '', error: 'foo' });
  }
Run Code Online (Sandbox Code Playgroud)

如何编写单元测试来检查我们是否获得了预期数据的预期异常?显而易见的解决方案是:

it('test', async () => {
  expect(await userController.doSomething())
    .rejects.toThrowError(new BadRequestException({ data: '', error: 'foo'});
});
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为new BadRequestException()创建了一个具有不同调用堆栈的对象。我该如何测试?

unit-testing exception jestjs nestjs

4
推荐指数
2
解决办法
2478
查看次数

标签 统计

exception ×1

jestjs ×1

nestjs ×1

unit-testing ×1