How to Debug my Mocha Test with Visual Studio Code

Visual Studio Code has a great feature that lets you debug your Node.js code. This feature gives you the typical F5 experience for running your Node application.  But what if what you want to do is run your Mocha test?  In this post I will show you how to set up the Visual Studio Code debugger to allow you to set breakpoints in your Mocha tests.

For this post I will assume you already have a Node.js project loaded in Visual Studio Code with Mocha tests. Follow the directions on the Visual Studio Code website to configure how your application will be started (Debugging your Node Application).

Now we are we are going to update the generated launch.json file to start your Mocha test.  Copy and paste the following code into your launch.json file:

{
   "version": "0.2.0",
   "configurations": [
      {
         "name": "Launch",
         "type": "node",
         "request": "launch",
         "program": "${workspaceRoot}\\node_modules\\mocha\\bin\\_mocha",
         "stopOnEntry": false,
         "args": [
            "${workspaceRoot}\\test\\appUnitTest.js"            
         ],
         "cwd": "${workspaceRoot}",
         "runtimeExecutable": null,
         "runtimeArgs": [
            "--nolazy"
         ],
         "env": {
            "NODE_ENV": "development"
         },
         "externalConsole": false,
         "sourceMaps": false,
         "outDir": null
      },
      {
         "name": "Attach",
         "type": "node",
         "request": "attach",
         "port": 5858,
         "sourceMaps": false,
         "outDir": null,
         "localRoot": "${workspaceRoot}",
         "remoteRoot": null
      }
   ]
}

With this code in place, simply update the args value (line 11) to point to your desired test file. Note the underscore before mocha on line 8. That is intentional. Now set breakpoints in your code and press F5 to debug your test.

Comments (3) -

  • intenter

    3/14/2016 8:04:12 AM | Reply

    Thanks for this post

  • pchiwan

    11/21/2016 4:58:08 PM | Reply

    Thanks, this was useful! I didn't get Mocha to launch from VSCode but I managed to attach to it after running mocha from the command line with --debug-brk!

    • Donovan

      11/27/2016 3:02:02 PM | Reply

      Make sure you point to "_mocha" and not mocha. It makes a big difference.

Add comment

Loading