DEV Community

Marco
Marco

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay