loading...

How to test exceptions in Jest

developarvin profile image Arthur Vincent Simon ・1 min read

How to use Jest .toThrow()

I initially thought that I could do this to unit test for errors

expect(doSomething()).toThrow()

Unfortunately, this doesn’t work. We need to wrap doSomething in another function in order for this to work

expect(() => doSomething()).toThrow()

//or

expect(function() { doSomething() }).toThrow()

Discussion

pic
Editor guide
 

Nice.

Just want to chip in to say we can skip the wrapping of the function like so:

expect(doSomething).toThrow()

(if we don't need to provide additional arguments)