How to test an exception was not thrown with Jest?

JavascriptUnit TestingError HandlingJestjs

Javascript Problem Overview


The Jest docs do not demonstrate a way of asserting that no exception was thrown, only that one was.

expect(() => ...error...).toThrow(error)

How do I assert if one was not thrown?

Javascript Solutions


Solution 1 - Javascript

You can always use the .not method, which will be valid if your initial condition is false. It works for every jest test:

expect(() => ...error...).not.toThrow(error)

https://jestjs.io/docs/expect#not

Solution 2 - Javascript

In my case the function being tested was asynchronous and I needed to do further testing after calling it, so I ended up with this:

await expect(
  foo(params),
).resolves.not.toThrowError();

// My other expects...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser9993View Question on Stackoverflow
Solution 1 - JavascriptAxnyffView Answer on Stackoverflow
Solution 2 - JavascriptCamiloView Answer on Stackoverflow