DEV Community

Marco A.
Marco A.

Posted on

Test if a promise throw an Error

Hi, few weeks ago I had to solve this problem,

If the API return 404 I want my code to Throw and error, in general fetch will not throw an error on API failure with exception of a time out so I had to force that behavior:

Here is my base code

const response = await fetch(url);
 if (!response.ok) {
    if(response.status !== 404){
        throw new Error(`Error on details API ${response.status}`)
      }
  }
Enter fullscreen mode Exit fullscreen mode

Ok... here the solution I end up with:

    await expect(
                api.fetchEvent(body)
    ).rejects.toThrow('Error on details API 404');
Enter fullscreen mode Exit fullscreen mode

It can be improved but I thought sharing the solution may help somebody else

Top comments (0)