Is it possible to add breakpoints to ones Mocha tests using Visual Studio Code?
Normally when debugging code one need to configure the launch.json, setting the program attribute to the javascript file to execute. I am not sure how to do this for for Mocha though.
In VSCode version 1.13.0 (macOS), they have it built-in under configurations ->
Mocha Tests
.I've figured out a way to do this which I classify as a workaround. I expect the Visual Studio Code team to provide a more definitive solution for this but meanwhile this what I've done:
./settings/mocha.js
file which runs mocha programatically passing arguments as a list of files to be run. You can see the full file here;I've created a launch config which will run the
./settings/mocha.js
as theprogram
and passes the files/file patterns we need to test as arguments:Full launch.json example
So this is the equivalent of doing
mocha test/unit/*.js test/unit/**/*.js
and now we can use breakpoints in our mocha tests.Here is an example of launch configuration (launch.json) from Microsoft, which works with Mocha and allows using the debugger.
Also, there is a description of how to use the --debug-brk option.
Finally, here is an alternative version of how to debug code with Mocha tests using tasks.json file of VS Code and Gulp task runner.
Did you know, that you just go into your launch config, put your cursor after or between your other configs and press ctrl-space to get a current, valid mocha config auto-generated?
Which works perfectly fine for me. Including stopping at breakpoints. ( I also had a prior, now outdated one, that did no longer for various setting-related reasons. )
As of VSCode 1.21.1 (March 2018) this yields:
On a side-note:
debug-brk
is deprectated (for anyone with Node >= Version 8 at least).If you don't want to use
--debug-brk
+Attach or state an absolute path to your global mocha installation (which will brake if you keep your launch.json under version control and have multiple developers on different machines), install mocha as a dev dependency and add this to your launch.json:Full debugging support in your tests by just pressing F5.
--no-timeouts
makes sure your tests don't time out because you stopped at a breakpoint, and--colors
makes sure Mocha outputs colors even though it doesn't detect that VS Code supports colors.When using Babel, or generating javascript files yet placing breakpoints in the source - you have to make sure to enable
sourceMaps
and defineoutFiles
. Here's an example config that worked for me.Note - you'll need to modify
outFiles
to include everything you might want to add a breakpoint to. This can be more tedious when in a monorepo and multiple dependent projects.