How to Debug Mocha Tests With Chrome

This post assumes you're familiar with Chrome's developer tools.

Take That, WebStorm!

I've long lamented that Vim will never have IDE style debugging, which is more powerful than any Vim feature. Until…

I was browsing the Mocha documentation on a whim while waiting patiently for death, when I came across this gem:

…mocha --debug will allow you to use a different interface — such as the Blink Developer Tools.

Allow me to what?!

Runtime Mocha Debugging With Chrome

1) Install node-inspector.

npm install -g node-inspector  

2) In a separate Terminal window, run node-inspector with no arguments.

node-inspector  

3) Go to http://127.0.0.1:8080/debug?port=5858 in Chrome.

4) Run your Mocha tests.

mocha [options] --debug-brk  

5) Go back to the browser. The --debug-brk tells the debugger to break on the first line of the first script. You're stopped inside of Mocha:

The debugger keyword is supported. One option is to put that in your test source beforehand.

Another option is to manually open your test files with ⌘o (splat-o) or use the file browser on the left side of the inspector. Then you can set breakpoints by hand.

Press ⌘\ (splat-backslash), or the resume script play icon, to jump to your first breakpoint. Now you can debug your tests as if you were in the Chrome console!

It's Not Perfect

You can leave node-inspector running forever, but you'll have to refresh the debugging page between runs. If it doesn't work, try launching Mocha first, then refreshing the page.

Minor grievances: It's fairly slow to load test files. The console output will have bash escape codes in it. It also doesn't have the benefit of being able to add a breakpoint by clicking in the gutter of your IDE. WebStorm still offers more efficient code to debugging flow.

You can't increase the font size like you can in the normal inspector with ⌘+ and ⌘-. If you're visually impaired or sleepy and have old contacts, like me, this is a bummer.

That's It!

If this blog post helped you increase your testing mojo, consider following me on Twitter or buying me a coffee :).

comments powered by Disqus