user9993
user9993

Reputation: 6170

How to test an exception was not thrown with Jest?

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?

Upvotes: 114

Views: 80086

Answers (3)

Aleksandr Chernyi
Aleksandr Chernyi

Reputation: 340

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

it('This should not throw an exception', async () => { await foo() });

Upvotes: 0

Camilo
Camilo

Reputation: 7184

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

Upvotes: 40

Axnyff
Axnyff

Reputation: 9944

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

Upvotes: 144

Related Questions