94

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?

frederj
  • 1,483
  • 9
  • 20
user9993
  • 5,833
  • 11
  • 56
  • 117

2 Answers2

121

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

agilgur5
  • 667
  • 12
  • 30
Axnyff
  • 9,213
  • 4
  • 33
  • 37
  • 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` – Bence Szalai May 06 '22 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 '22 at 14:44
29

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...
Camilo
  • 6,504
  • 4
  • 39
  • 60