笑话掩盖块

问题描述

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

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块的测试如下:

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);
  }
});

正如我所说,伊斯坦布尔并未显示出经过测试的捕获块。我该怎么做才能达到100%的覆盖率?

解决方法

通常,您不应该在测试fn中使用try / catch。由于您使用的是异步/等待,请尝试使用.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,() => {
  const invalidUser = new User();
  
  expect(service.create(invalidUser)).toThrowError(BadRequestException);
});