125

Is it possible to add breakpoints to Mocha tests using Visual Studio Code?

Normally when debugging code, one needs to configure the launch.json, setting the program attribute to the Javascript file to execute. I am not sure how to do this for Mocha though.

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
André Vermeulen
  • 1,774
  • 4
  • 17
  • 26

22 Answers22

110

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. )

enter image description here

As of VSCode 1.21.1 (March 2018) this yields:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Mocha (Test single file)",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "${workspaceRoot}/node_modules/.bin/mocha",
        "--inspect-brk",
        "${relativeFile}",
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "port": 9229
    }
}

On a side-note: debug-brk is deprectated (for anyone with Node >= Version 8 at least).

Nick
  • 1,174
  • 11
  • 20
Frank N
  • 9,625
  • 4
  • 80
  • 110
  • 2
    I had some custom code needed to initialize the document and disable Hot Module Replacement. Pass this argument in the `"args"` block: `"--require", "${workspaceFolder}/tools/testSetup.js",` – Kent Bull Mar 16 '18 at 21:56
  • 1
    VS Code 1.29.1: The `Ctrl+Space` autogenerated Mocha Tests config did not have `debug-brk`. Despite that debugging with breakpoints worked just fine. – HelloWorld101 Dec 17 '18 at 16:10
  • @Antony Yes, for long `debug-brk` it is no longer needed used, supported or auto-inserted. My _side-note_ only clarified this, as multiple other answers mention it. – Frank N Dec 18 '18 at 11:10
  • 2
    I had to insert a comma after the right brace of my (only) other configuration for `ctrl + space` to work. – GOTO 0 May 05 '19 at 07:53
  • Control-space had no effect, but the actual configuration snippet worked. For newcomers - to get the file to put the snippet in in the first place, first open your project directory with File -> Open. Then go back to the debugging view and press the gear icon to create launch.json, where you can paste the snippet. Then set breakpoints by clicking to the left of line numbers, select your file to run and try the green play icon to the left of the gear icon. – nsandersen Jun 26 '19 at 09:15
  • 3
    For an up-to-date example of proper configuration for Mocha see: https://github.com/Microsoft/vscode-recipes/tree/master/debugging-mocha-tests – Nux Jan 06 '20 at 00:28
  • Just wanted to throw out there that the new "pwa-node" type is somewhat necessary for debugging mocha internals with newer versions of mocha and VSCode – dracstaxi Jul 21 '20 at 17:09
  • 2
    FYI, the accepted answer @ https://stackoverflow.com/a/55883516/684271 reveals what had to be removed as of Nov 2020. – Peter Majeed Nov 02 '20 at 03:07
73

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:

{
  "name": "mocha",
  "type": "node",
  "request": "launch",
  "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
  "stopOnEntry": false,
  "args": ["--no-timeouts", "--colors"], //you can specify paths to specific tests here
  "cwd": "${workspaceRoot}",
  "runtimeExecutable": null,
  "env": {
    "NODE_ENV": "testing"
  }
}

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.

Matt Bierner
  • 58,117
  • 21
  • 175
  • 206
felixfbecker
  • 2,273
  • 1
  • 19
  • 24
  • 13
    For anyone else having trouble. Note the _mocha and not mocha. With only mocha it will run the tests in VS code but the breakpoints are not hit – tkarls Dec 01 '16 at 10:39
  • 2
    For those using TypeScript, this is a suitable answer so long as you set `sourceMaps: true`. Thanks a billion! – Bryan Rayner Dec 17 '16 at 21:41
  • 1
    To add your npm compatible custom test params, add something like `npm_config_myparam` to the env block. Where on the CLI, it might look like `npm --myparam=myvalue test`. – bvj Aug 23 '17 at 05:54
45

Another way is to use the --debug-brk command line option of mocha and the default Attach launch setting of the Visual Studio Code debugger.


Suggested deeper explanation (from André)

To do this:

Run mocha from the command line using this command:

mocha --debug-brk

Now in VS Code click on the Debug icon, then select Attach from the option next to the start button. Add breakpoints in VS Code and then click start.

Wolfgang Kluge
  • 895
  • 8
  • 13
  • 2
    This way is much easier, there's virtually no configuration – André Vermeulen May 16 '15 at 11:49
  • You must add `"request": "attach"` to the launch.json if it doesn't exist - otherwise it will complain that you must specify a program or some other error. – jocull Feb 01 '16 at 16:00
  • This seems to be `VS Code` specific. Doesn't work in normal VS 2015 – Pavel P Aug 31 '16 at 13:27
  • great advice Thanks :) – Gaurav Rawat Dec 20 '16 at 20:34
  • 1
    Note, that `--debug-brk` is [nowadays deprecated](https://github.com/Microsoft/vscode/issues/32529), that's why I suggest [auto-creating a fresh debug config in vscode](https://stackoverflow.com/a/46977963/444255), yes, alslo specifically for mocha. – Frank N Oct 31 '17 at 10:09
  • this worked for me however i had first changed my vscode config per this article first https://itnext.io/the-absolute-easiest-way-to-debug-node-js-with-vscode-2e02ef5b1bad unsure if that helps anyone – iamnotsam Dec 04 '19 at 01:42
26

I've made this work on VSCode on OS X 10.10. Just replace your ./settings/launch.json file with this.

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Run app.js",
            "type": "node",
            "program": "app.js", // Assuming this is your main app file.
            "stopOnEntry": false,
            "args": [],
            "cwd": ".",
            "runtimeExecutable": null,
            "env": { "NODE_ENV": "production"}
        },
        {
            "name": "Run mocha",
            "type": "node",
            "program": "/Users/myname/myfolder/node_modules/mocha/bin/_mocha",
            "stopOnEntry": false,
            "args": ["test/unit.js"],
            "cwd": ".",
            "runtimeExecutable": null,
            "env": { "NODE_ENV": "production"}
        }
    ]
}

It is also available as a gist here.

The key values you need to change are program, which should be set to the _mocha executable, and args, which should be an array of your test files.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
GPX
  • 3,506
  • 10
  • 52
  • 69
  • Doesn't work for me (on windows) - but seems like a good solution if it works :) – Wolfgang Kluge May 18 '15 at 12:09
  • Yes. Sorry `OpenDebug process has terminated unexpectedly` – Wolfgang Kluge May 18 '15 at 12:25
  • Can you try setting `"runtimeExecutable"` to `"C:/Program Files/nodejs/node.exe"` or wherever Node is installed? – GPX May 18 '15 at 12:58
  • For sure - but no change. – Wolfgang Kluge May 18 '15 at 13:02
  • I don't use Windows, so I can't help any further. However, keep an eye on [this](http://stackoverflow.com/a/30002073/398713) - they're talking about this OpenDebug issue. – GPX May 18 '15 at 13:05
  • On Windows, I run this but the breakpoints are ignored. I set stopOnEntry to true, so VSCode will let me step through code. However, if I hit F5, mocha run nonstop, showing the expected results in the console, but it completely ignores my breaks. – Bruno Brant May 11 '16 at 20:39
15
  1. Go to Debug > Add Configuration... menu
  2. Select Node.js environment
  3. Select Mocha Tests option from the appeared drop-down list
  4. Type the path of your test file as the last item of the args property
  5. Add a breakpoint
  6. Click on Debug icon
  7. Select Mocha Tests as a configuration
  8. Press Start debugging button
  9. :-)
Yas
  • 4,957
  • 2
  • 41
  • 24
12

The way I got it to work on VS Code (1.8.2) on Mac OS X is:

{
    "name": "Mocha",
    "type": "node",
    "request": "launch",
    "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
    "stopOnEntry": false,
    "args": ["--recursive"], //you can specify paths to specific tests here
    "cwd": "${workspaceRoot}",
    "runtimeExecutable": null,
    "env": {
        "NODE_ENV": "testing"
    }
}

Mocha needs to be installed in the npm modules directory.

Matt Bierner
  • 58,117
  • 21
  • 175
  • 206
mikebz
  • 3,277
  • 8
  • 37
  • 50
  • This had me stuck for ages. I incorrectly used the path from "which mocha" rather than node_modules. Thanks! – PMac Dec 15 '16 at 06:43
6

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:

  1. I've created a ./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;
  2. I've created a launch config which will run the ./settings/mocha.js as the program and passes the files/file patterns we need to test as arguments:

    {
        "name": "Unit tests",
        "type": "node",
        "program": ".settings/mocha.js",
        "stopOnEntry": true,
        "args": ["test/unit/*.js", "test/unit/**/*.js"],
        "cwd": ".",
        "runtimeExecutable": null,
        "env": { }
    }
    

    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.

Dário
  • 2,002
  • 1
  • 18
  • 28
  • Doesn't work for me, it can't find the test files, paths are correct I tried also with full paths. – Simone Gianni Sep 29 '15 at 16:26
  • 1
    This works for me too vscode 0.10.6. With breakpoints in .ts files, with sourcemaps, I did add `'sourceMaps': true, 'outDir': './build'` to my launch configuration. – pyrho Feb 08 '16 at 11:10
4

If you add ${file} variable at the end of the args list you can start debugging directly from the file you have open:

        {
            "type": "node",
            "request": "launch",
            "name": "Mocha Tests",
            "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
            "args": [
                "-u",
                "tdd",
                "--timeout",
                "999999",
                "--colors",
                "${file}"
            ],
            "internalConsoleOptions": "openOnSessionStart"
        }
Eugene Kulabuhov
  • 2,349
  • 1
  • 26
  • 25
2

Sorry for adding yet another answer, but none of the previous ones quite worked for me as of VS Code 1.8.1 and the standard Node debugger included in it. Here is the way I solved it (with guidance from the previous answers here and from the official VS Code Node.js Debugging docs) so there is one click/keypress debugging:

  • Ensure mocha is installed as a devDependency in packages.json: "devDependencies": { "mocha": "^3.2", ... }
  • Run npm install in the directory of your package.json to make sure mocha is now installed in node_modules/
  • Open .vscode/launch.json (or in VS Code, press F1, start typing "launch", and select "Debug: Open launch.json")
  • Click the blue "Add Configuration" button in the bottom right (or just copy and paste one of your others); this step is optional... I mean, you can re-use an existing config. But I suggest adding one to keep it less confusing.
  • Change the following in your launch.json, then pick the new config name in the debug window in VS Code and click the green arrow to start debugging your node + mocha tests!

In the new config in launch.json:

"configurations": [{
    "name": "whatever name you want to show in the VS Code debug list",
    "type": "node",
    "cwd": "${workspaceRoot}",
    "program": "${workspaceRoot}/node_modules/mocha/bin/mocha",
    "args": ["--debug-brk=5858", "--no-timeouts", "--colors", "test/**/*.js"],
    "address": "localhost",
    "port": 5858,
    // the other default properties that are created for you are fine as-is
}, ...]

This assumes the pattern test/**/*.js will work for where you put your tests. Change as appropriate.

Feel free to change the port as long as you change it in both of the args and port properties to match.

The key differences for me was making sure mocha was in node_modules, using program to point to the executable, and args needing debug-brk=x pointing to the port specified in port. The rest of the above just makes things prettier and easier.

It's up to you and your team if you put .vscode/launch.json in the repository or not. It's an IDE-only file, but your whole team could use it like this, no problem, since all paths and installs are relative and explicit.

Tip: The package.json can include a scripts tag that also launches mocha with something like "test": "./node_modules/.bin/mocha", but it is not used by VS Code—instead it is used when npm test is run at the command line. This one confused me for a bit. Noting it here in case others get confused too.

EDIT: VS Code 1.9.0 has added an "Add Configuration" option in the debug configuration drop-down, and you can pick "Node.js Mocha Tests" which help simplify most of the above. You still need to make sure mocha is in your node_modules and might have to update the cwd and last runtimeArgs (which is the pattern for finding your tests) to point to the appropriate paths. But once you set those two properties, it should work pretty much from there.

Jon Adams
  • 24,464
  • 18
  • 82
  • 120
2

in the launch.json, add 1 more configuration below

{
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
      "args": [
        "--timeout",
        "10000",
        "${workspaceRoot}/services/*.spec.js",
        "${workspaceRoot}/*.spec.js"
      ],
      "internalConsoleOptions": "openOnSessionStart"
    },

if you need to configure node version, simply add runtimeExecutable field like this

{
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
      "args": [
        "--timeout",
        "10000",
        "${workspaceRoot}/services/*.spec.js",
        "${workspaceRoot}/*.spec.js"
      ],
      "internalConsoleOptions": "openOnSessionStart",
      "runtimeExecutable": "${env:HOME}/.nvm/versions/node/v8.2.1/bin/node"
    },
Alongkorn
  • 3,968
  • 1
  • 24
  • 41
2

1) Go to

.vscode

then

launch.json

file

2) Add the following configuration in launch.json -

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Mocha Test",
            "cwd": "${workspaceRoot}",
            "runtimeExecutable": "${workspaceRoot}/*folder_path_containing_test*/node_modules/.bin/mocha",
            "windows": {
                "runtimeExecutable": "${workspaceRoot}/*folder_path_containing_test*/node_modules/.bin/mocha.cmd"
            },
            "runtimeArgs": [
                "--colors",
                "--recursive",
                "${workspaceRoot}/*folder_path_till_test*/tests"
            ],
            "internalConsoleOptions": "openOnSessionStart"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/*folder_path_to_test*/app.js"
        }
    ]
}

3) Set breakpoints in test file and then press F5

MERLIN THOMAS
  • 747
  • 1
  • 7
  • 15
1

For anyone using Windows. If you have installed mocha globally then setting program to the following path worked for me (swap in your username).

"program": "C:\\Users\\myname\\AppData\\Roaming\\npm\\node_modules\\mocha\\bin\\_mocha"
JayChase
  • 11,174
  • 2
  • 43
  • 52
1

This is working fro me on a Windows 7 machine. I do have mocha installed globally, but this configuration is pointing to the project install to avoid the need for a user profile path (which btw, I tried used %USERPROFILE% variable with no success). I'm able to set breakpoints in my mocha tests now. Yay!

{
        "name": "Mocha Tests",
        "type": "node",
        "request": "launch",
        "stopOnEntry": false,
        "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
        "cwd": "${workspaceRoot}",
        "args": ["./test/**/*.js"],
        "runtimeExecutable": null,
        "envFile": "${workspaceRoot}/.env"
    }
rspring1975
  • 103
  • 1
  • 9
1

For those that are using grunt or gulp, the configuration is pretty simple.

Launch.json

{
"version": "0.2.0",
"configurations": [

    {
        "name": "Run mocha by grunt",
        "type": "node",
        "program": "${workspaceRoot}/node_modules/grunt/bin/grunt",
        "stopOnEntry": false,
        "args": ["mochaTest"],
        "cwd": "${workspaceRoot}",
        "runtimeExecutable": null
    }
]}

Gruntfile.js

module.exports = function (grunt) {

grunt.initConfig({
    mochaTest: {
        test: {
            options: {
                reporter: 'spec'
            },
            src: ['test/**/*test.js']
        }
    }
});

grunt.loadNpmTasks('grunt-mocha-test');

grunt.registerTask('default', 'mochaTest');};
Leandro Rodrigues
  • 1,134
  • 1
  • 8
  • 13
1

In VSCode version 1.13.0 (macOS), they have it built-in under configurations -> Mocha Tests.

mattyb
  • 1,011
  • 2
  • 10
  • 26
1

When using Babel, or generating javascript files yet placing breakpoints in the source - you have to make sure to enable sourceMaps and define outFiles. Here's an example config that worked for me.

    {
        "name": "Mocha Test",
        "type": "node",
        "request": "launch",
        "program": "${workspaceRoot}/packages/api/node_modules/mocha/bin/_mocha",
        "cwd": "${workspaceRoot}/packages/api",
        "args": ["--colors", "--no-timeouts", "out/test"],
        "outFiles": ["${workspaceRoot}/packages/api/out/*"],
        "sourceMaps": true,
    },

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.

ubershmekel
  • 11,864
  • 10
  • 72
  • 89
1

The official microsoft/vscode-recipes on Github has this launch.json for debugging mocha tests (enter the link for more mocha tests configurations):

{
  "version": "0.2.0",
  "configurations": [
    {
        "type": "node",
        "request": "launch",
        "name": "Mocha All",
        "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
        "args": [
            "--timeout",
            "999999",
            "--colors",
            "${workspaceFolder}/test"
        ],
        "console": "integratedTerminal",
        "internalConsoleOptions": "neverOpen",
        "skipFiles": [
            "<node_internals>/**/*.js"
        ]
    },
    {
        "type": "node",
        "request": "launch",
        "name": "Mocha Current File",
        "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
        "args": [
            "--timeout",
            "999999",
            "--colors",
            "${file}"
        ],
        "console": "integratedTerminal",
        "internalConsoleOptions": "neverOpen",
        "skipFiles": [
            "<node_internals>/**/*.js"
        ]
    }
  ]
}
OfirD
  • 9,442
  • 5
  • 47
  • 90
0

When using TypeScript, the following configuration works for me in Visual Studio Code 0.8.0 (tsc 1.5.3)

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "outDir": "build",
        "declaration": false
    },
    "files": [
        "./src/index.ts",
        "./src/test/appTests.ts"
    ]
}

The important things to note here is that source maps are generated and that the output directory for the js is set to build

launch.json

    {
        "name": "Attach",
        "type": "node",
        // TCP/IP address. Default is "localhost".
        "address": "localhost",
        // Port to attach to.
        "port": 5858,
        "sourceMaps": true,
        "outDir": "build"
    }

Please note that sourceMaps is set to true and that the outDir is set to build

to debug

  1. Stick breakpoints in index.ts any other imported typescript file
  2. Open a terminal and run : mocha --debug-brk ./build/test/appTests.js
  3. From VSC, run the 'Attach' launch configuration
Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101
0

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.

javaeeeee
  • 681
  • 8
  • 13
0

If you have some dependency in the test it is also easy to attach it.

For example, I am using mongo-unit-helper to also have unit tests integrated with Database.

package.json script is: mocha --recursive --require ./test/mongo-unit-helper.js --exit"

My launch.json looks like:

  "configurations": [
  {
  "type": "node",
  "request": "launch",
  "name": "Mocha Tests",
  "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
  "args": [
    "-u",
    "tdd",
    "--timeout",
    "999999",
    "--colors",
    "--recursive",
    "--require",
    "${workspaceFolder}/test/mongo-unit-helper.js",
    "${workspaceFolder}/test/**/*.js",
  ],
  "internalConsoleOptions": "openOnSessionStart"
 }
]

Solution is to put --require separately in args in launch.json.

airen
  • 5
  • 4
0

Simplest solution

Add the following code to the launch.json inside the .vscode folder :

{
            "name": "Unit tests",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
            "args": [
            ],
        }

You might want however to add a timeout argument as well:

 {
            "name": "Unit tests",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
            "args": [
                "--timeout",
                "999999"
            ],
        }
Cap Barracudas
  • 2,347
  • 4
  • 23
  • 54
0

So, I had this problem when using a monorepo (e.g. /repo/sub-repo) which had a subfolder with a package.json and its own mocha configuration, but was launching mocha in the debugger from the root folder rather than the sub-folder. Switching to the sub-folder and creating a mocha configuration there solved the problem completely.