Last Updated: 10/22/2015
While working on a recent GitHub pull request for OmniSharp’s ASP.NET 5 Yeoman generator, I needed to test my changes prior to submitting. Unfortunately, one of the pre-existing tests was failing on Windows with the latest version of Node (v4.0+); and, I wanted to dig deeper to understand the root cause. Having never debugged Mocha unit tests in VS Code, I was reluctantly venturing into uncharted territory. What follows is a summary of steps required to setup the desired debugging experience.
Show Me the Steps!
As described in the “Usage” section of Mocha’s Getting Started page, there’s a
Stash that command away in a package.json script, and you’ll never have to remember or type it again:
Specifically, the reserved test script may be a great fit for this. I stress “reserved” because that means the run keyword isn’t required to execute the script. Run it like this in the command shell:
At the time of writing, I’m using VS Code 0.9.1. Unfortunately, NPM scripts aren’t yet discoverable by VS Code’s Command Palette; however, it is a highly requested feature which is under consideration for a future release. For now, open a command shell and run this command from there. An informative message will appear in the console stating that a debugger is listening on a certain port (see the screenshot below). Take note of that port number, as you’ll need to reference the same number in VS Code.
Return to VS Code. If a launch.json file doesn’t already exist within the .vscode folder of your project, now is the time to create it. Its contents should resemble the gist below. Remember that port number you were supposed to jot down? Here’s where it will be needed.
Now that the debugger configuration file has been created, set a breakpoint on the Mocha test which you’d like to troubleshoot. Next, click the VS Code side bar’s Debug tab, and select the appropriate debugging configuration option from the drop-down list to the right of the green play button. In this example, that debugging configuration name is “Debug Mocha Test”. Once selected, click the green play button. The debugging session has been started, and the typical debugging controls are provided to step into, step out, step over, etc.