DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Arthur Vincent Simon
Arthur Vincent Simon

Posted on

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 on

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)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!