98

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?

2
  • 1
    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? Apr 1, 2018 at 22:53
  • How would you test that if you needed that kind of test?
    – user9993
    Apr 1, 2018 at 23:13

2 Answers 2

125

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

2
  • 1
    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: undefined May 6, 2022 at 21:38
  • 3
    @sbnc.eu It works also for void return type if you wrap it into a function. expect(() => myvoidreturnfunction()).not.toThrow()
    – LiMuBei
    May 30, 2022 at 14:44
34

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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.