How to debug Jest tests with VSCode

Matt Mazzola
2 min readMay 6, 2017

--

Note: I have published an updated article on this topic here

I recently started using Jest to write and run my tests and I liked almost everything about it except it seems to be missing clarity on how to setup the debug workflow. Often times when the library or set of components under test become more and more complex it is not enough to simply see pass or fail with the actual result and expected result. I would need to understand why the actual result differed and how it was computed incorrectly. Being able to put breakpoints in my tests and then step through the source with the inputs from the tests was a valuable part of my workflow on my previous setup using jasmine and karma.

With Jasmine and Karma, there were chrome launcher plugins that would would open chrome with an generated test runner page which invoked the tests and there I could use Chrome development tools to do my debugging. This worked out well and I wanted something similar for Jest.

After looking at their documentation, github issues, and stackoverflow answers it is possible using a command such as:
node --debug-brk --inspect ./node_modules/.bin/jest -i

However, this only prints out a url to open chrome dev tools such as:

`chrome-devtools://devtools/remote/serve_file/@521e5b7e2b7cc66b4006a8a54cb9c4e57494a5ef/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node`

As far as I know, you then have to copy paste this URI in to chrome which is a cumbersome step in the process. Assuming debugging happens rarely perhaps this is acceptable; however, when I tried it I was unsuccessful at debugging.
Devtools does stop executing for you; however, because the files that your test are in have not been loaded yet you cannot set breakpoints on them. If you press f8 or Continue to it will load files and execute tests before you have opportunity to set break points within them. Basically Catch-22 debug experience.

After enough frustration, I decided to investigate how to debug directly within VSCode since it has been very nice experience when debugging other node applications and in my particular case i was only interested in debugging TypeScript libraries and did not need a browser.

For this I started investigating VSCode launch configurations and came up with the magic snippet here:

Essentially VSCode knows this is intended to be a node debugging launch based on the type. It will implicitly detect debug mode (lecacy or inspect) and construct appropriate node debug command such as:node --debug-brk=30547 --no-lazy (notice the randomly generated port) and the append the rest of your configuration such as node_modules\jest\bin\jest.js -i

Hope that helped you and make your testing experience more enjoyable. Let me know in the comments if you have a better debug configuration for VS Code perhaps using pre-processor or if you find a way to properly use Chrome Dev tools solution.

--

--