How to test an exception was not thrown with Jest?
Asked Answered
A

3

107

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?

Afterdeck answered 1/4, 2018 at 22:48 Comment(2)
If you have an uncaught exception, your tests will fail. Is there a situation where many different type of exceptions can be thrown except one type?Tatary
How would you test that if you needed that kind of test?Afterdeck
P
135

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

Passional answered 1/4, 2018 at 22:49 Comment(2)
I'm wondering if this can handle functions with void return type? I'm getting Error: expect(received).not.toThrowError() \n Matcher error: received value must be a function \n Received has value: undefinedBaccarat
@sbnc.eu It works also for void return type if you wrap it into a function. expect(() => myvoidreturnfunction()).not.toThrow()Alex
M
39

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...
Mastaba answered 6/4, 2022 at 14:12 Comment(0)
B
0

In my case I test my asynchronous function that simple way:

it('This should not throw an exception', async () => { await foo() });
Baumgartner answered 18/4 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.