DEV Community

Arthur Vincent Simon
Arthur Vincent Simon

Posted on

3 1

How to test exceptions in Jest

How to use Jest .toThrow()

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

expect(doSomething()).toThrow()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sargalias profile image
Spyros Argalias • Edited

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)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more