簡體   English   中英

笑話封面捕捉塊

[英]Jest cover catch blocks

我在 typescript 有一個簡單的方法,看起來像這樣

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

我的目標是讓這個 function 達到 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);
});

如果沒有斷言被拒絕的 promise 您可以使用.toThrow()toThrowError()代替:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM