笑话盖挡块

Jest cover catch blocks

我在打字稿中有一个简单的方法,看起来像这样

async create(user: User): Promise<User> {
    try {
      return await this.userRepository.save(user);
    } catch (exp) {
      throw new BadRequestException('Failed to save user');
    }
}

我的目标是使此功能达到 100% 的代码覆盖率。测试 try 块工作正常。但是我无法使用 Jest 覆盖伊斯坦布尔的 catch 块。我对 catch 块的测试如下所示:

it('should throw an error when user is invalid', async () => {
  const invalidUser = new User();
  try {
    await service.create(invalidUser);
  } catch (exp) {
    expect(exp).toBeInstanceOf(BadRequestException);
  }
});

正如我所说,伊斯坦布尔没有显示经过测试的 catch 块。我应该怎么做才能达到此方法的 100% 覆盖率?

通常你不应该在测试 fn 中使用 try/catch。由于您使用的是 async/await,请尝试使用 .rejects.toThrow():

it('should throw a BadRequestException, when user is invalid', async () => {
  const invalidUser = new User();
  
  await expect(service.create(invalidUser)).rejects.toThrow(BadRequestException);
});

如果不声明被拒绝的承诺,您可以使用 .toThrow() or toThrowError() 代替:

it('should throw a BadRequestException, when user is invalid', () => {
  const invalidUser = new User();
  
  expect(service.create(invalidUser)).toThrowError(BadRequestException);
});