jeudi 13 août 2020

Jest cover catch blocks

I've a simple method in typescript which looks like this

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

My goal is to reach 100% code coverage for this function. Testing the try block work's fine. But I can't get coverage for the catch block in Istanbul using Jest. My test for the catch block looks like this:

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

As I said Istanbul dosen't show the catch block as tested. What should I do to reach 100% coverage for this method?

Aucun commentaire:

Enregistrer un commentaire