我在typescript中有一个简单的方法,看起来像这样
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%覆盖率?
发布于 2020-08-15 12:22:07
通常,您不应该在测试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);
});https://stackoverflow.com/questions/63402746
复制相似问题