Can Visual Studio Code be configured to launch with nodemon - node.js

I have installed nodemon as a global package in my system.
It works when I executed nodemon in cmd.
But when I am using vscode with this launch.json file, vscode throws this exception:
request launch: runtime executable XXX\XXX\XXX\XXX\nodemon does not exists
the launch.json is:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "node",
"request": "launch",
"program": "app.js",
"stopOnEntry": false,
"args": [],
"cwd": ".",
"runtimeExecutable": nodemon,
"runtimeArgs": [
"--nolazy"
],
"env": {
"NODE_ENV": "development"
},
"externalConsole": false,
"preLaunchTask": "",
"sourceMaps": false,
"outDir": null
},
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 5858
}
]
}
when I erase the nodemin in runtimeExecutable it runs perfectly with node

First, install nodemon as a dev dependency:
npm install --save-dev nodemon
For newer versions of VS Code set up your .vscode/launch.json file like this:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "nodemon",
"runtimeExecutable": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js",
"program": "${workspaceFolder}/app.js",
"restart": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}]
}
The most important pieces are the runtimeExecutable property that points to the nodemon script and the program property that points to your entry point script.
If you use an older VS Code (which you shouldn't), try this launch configuration:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch with nodemon",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/node_modules/nodemon/bin/nodemon.js",
"args": ["${workspaceRoot}/app.js"],
"runtimeArgs": ["--nolazy"]
}
]
}
The most important pieces are the program property that points to the nodemon script and the args property that points to your normal entry point script.

I couldn't get #AdrianT's answer working with the debugger attached. It seems like there's a newer built-in supported way to do this:
Open the Launch Configuration dropdown and select "Add configuration..."
Select "Node.js: Nodemon Setup"
It will add something like this to your launch.json:
{
"type": "node",
"request": "launch",
"name": "nodemon",
"runtimeExecutable": "nodemon",
"program": "${workspaceRoot}/app.js",
"restart": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
Make sure your "program" setting is your correct entry point script.
You need to install nodemon globally to get this to work (npm install -g nodemon) (as per the documentation)
Your app now runs and you can set breakpoints which will be hit and the console logs to the integrated terminal window.
Note that terminating the debug session only terminates the program to debug, not nodemon itself. To terminate nodemon, press Control-C in the integrated terminal.

In Visual studio code create a launch config:
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 5858,
"restart": true
}
run nodemon from the command line: nodemon --debug server.js
Now 'Attach' from VC and vuala.

Attaching is definitely an easy option. In order to make sure that your code breaks, make sure you run nodemon with --inspect-brk (node 8+), e.g.:
nodemon --inspect-brk src/app.js
After launching nodemon will log the port open for debug connections:
Debugger listening on ws://127.0.0.1:9229/someUUID
You can take that port in order to build your launch config which is quite simple:
{
"type": "node",
"request": "attach",
"name": "Attach",
"port": 9229,
"restart": true
},

I tried the solutions Adrian and Mathew suggested. They seem to work perfectly if your are on macOS (maybe also on Linux). On Windows, maybe Mathew's solution is more stable. Combining both to have a solution that could be compatible with both macOS, Windows and Linux, and makes sure that we don't face with errors like "PATH not found", I found that using globally installed nodemon for debugging seems to be much more stable.
Install nodemon globally (if you haven't done it before) npm i -g nodemon
Add the following to the .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug App_Name",
"skipFiles": [
"./path/of/file/to/skip/when/debugging"
],
"program": "app.js",
"restart": true,
"runtimeExecutable": "nodemon",
"console": "integratedTerminal"
}
]
}
We, of course, can still install nodemon locally and run it while developing.

What worked for me without global installs and using typescript:
{
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"name": "nodemon",
"program": "${workspaceFolder}/src/index.ts",
"request": "launch",
"restart": true,
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/nodemon",
"type": "pwa-node",
"args": ["--config", "nodemon.json"] //remove --config if you don't have one
}
In order to don't have problems with ts-node, in nodemon.json I added it:
{
"execMap": {
"ts": "npx ts-node"
}
}

No, currently it can't. But I managed to get this somewhat working using nodemon. I start it from Grunt . But an equivalent command line should do the same.
EDIT: After an evening of testing I can say that below approach is still somewhat flakey :S, attaching fails intermittedly and sometimes breakpoints are ignored.
EDIT2: You can also specify an non default debug port in Gruntfile using ['--debug-brk=5860'] for nodeArgs. I've been also advised to use --debug-brk instead of --debug. Perhaps this will remove the current flakeyness. I'll come back and mention here if it helps (I've currently switched project).
In case this might help anyone it's working with below settings in Current VS Code version (e.g. v0.10.6) on Windows 10. But it'll probably work on Mac too (I might check later). But note that I sometimes have to trigger a rebuild by changing+saving a file before the debugger picks it up.
/.vscode/launch.json
{
"configurations": [{
"name": "Launch",
"outDir": null
},{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 5858
}]
}
/Gruntfile.js
nodemon : {
dev : {
script : 'launcher.js'
},
options : {
ignore : ['node_modules/**', 'Gruntfile.js'],
nodeArgs: ['--debug'],
env : { PORT : '4123'
}
}
}
I guess the debug port 5858 is the default since it's not specified here (note it ís in launch.json above.)

https://github.com/Microsoft/vscode-recipes/tree/master/nodemon
The above link helped me to successfully debug nodemon + express app. The steps are well explained there.
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Node: Nodemon",
"processId": "${command:PickProcess}",
"restart": true,
"protocol": "inspector",
}
]
}
npm script
"dev-server": "nodemon ***--inspect*** server.js"
Steps:
Run the server, using npm script. Please note --inspect arg in
the script
Start visual code debugger, A prompt will be shown to
select the node server process
select the node server process
Now you should be able to debug.
if it did not help you, then please have a look at the official doc, the config options are explained there.
https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_launch-configuration-support-for-npm-and-other-tools

This will let you run it on the file currently open in the editor WITHOUT installing nodemon as a dependency. This makes it convenient to keep in a template project.
The cwd and program are set so that the working directory is the one containing the file, and the program is the filename without a path. This makes it compatible with monorepos because it will then search back up the file tree for the correct tsconfig.json, package.json, node_modules, etc.
E.g. if the currently opened file is /path/to/some-file.ts, this is equivalent to running in the shell like:
cd /path/to
npx -y nodemon some-file.ts
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "nodemon",
"runtimeExecutable": "npx",
"runtimeArgs": ["-y", "nodemon"],
"program": "${file}",
"cwd": "${fileDirname}",
"restart": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}

Yes you can! As of a recent update you can attach the debugger to a running Nodemon process. This page has more information. Search for nodemon on the page to see the instructions.

I use the Node Exec plugin. It allows you to run and stop a node app in vcs by pressing F8 and F9 (applies on open file in editor). This could help as a (temporary) workaround.

Nodemon as local dependency
I also could not get #Adrian T's answer to work right away. But it is only a small detail, that has to be changed to make it work. So here we go:
create a launch.json file in a top-level .vscode folder
open the file in VS Code
use the build in button Add Configuration - that will be rendered in the editor - to add a config for Node.js: Nodemon Setup
in the generated config change the key runtimeExecutable:
"program": "${workspaceFolder}/app.js",
// diff from Adrian T
-- "runtimeExecutable": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js",
++ "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/nodemon",
You are now using the executables from your local dependencies (see this SO thread)
There is also an answer by Martin from earlier underneath this answer (just to be correct):
If you don't like having to run a global nodemon you can also install nodemon using npm and then set "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/nodemon", – Martin Feb 22 '18 at 22:25
Nodemon as global dependency
"runtimeExecutable": "nodemon", will only work if the executable of nodemon itself is part of the environment variable PATH (not `%appdata% or the like thereof). As this is mostly not the case, you would need to specify the absolute path (see the docs here and here).

For anyone trying to set up nodemon with an express-generator created ExpressJS project on windows, this is what worked for me when nodemon is installed as a local dev dependency (e.g. npm install nodemon --save-dev)
{
"type": "node",
"request": "launch",
"name": "Launch with Nodemon",
"runtimeExecutable": "node",
"runtimeArgs": ["${workspaceFolder}/node_modules/nodemon/bin/nodemon.js"],
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\bin\\www",
"env" : {
"DEBUG": "myapp:server"
}
}

No need to do anything,
Just open Powershell as administrator and write
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
and then enter A

1. Install nodemon as a dev dependency.
npm install -D -E nodemon
Options:
-D option: To save as dev dependency
-E option: To install exact version
2. Add a nodemon.json file in the root of the project with the following content.
{
"restartable": "rs",
"ignore": [".git", "node_modules/**/node_modules"],
"verbose": true,
"execMap": {
"js": "node --harmony"
},
"watch": ["src/", ".env"],
"env": {
"NODE_ENV": "development"
},
"ext": "js,json",
"delay": 500
}
For more information, see the official documentation here.
3. Add a script to package.json.
npm pkg set scripts.dev="nodemon --config nodemon.json"
4. Add launch config in .vscode/launch.json.
Content:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Run Nodemon",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "dev"],
"envFile": "${workspaceFolder}/.env",
}
]
}
To see documentation here.
The envFile option is optional. I use it because I am using dotenv.

It works fine for me, in the main Terminal.
Do not use VS code terminal, use the main system terminal.

Related

VsCode launch json configuration for specific node version and use yarn start

Couldn't find a solution to run yarn start in vscode debugger mode using a specific node version. launch.json file is as follows
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch via Yarn",
"runtimeExecutable": "${env:HOME}/.nvm/versions/node/v14.20.0/bin/node",
"cwd": "${workspaceFolder}",
"runtimeArgs": ["start:debug"]
}
]
}
Any additional config to do this?
I'm using nvm for development.
NVM relies on environment variable set in the shell, so make sure the setting shell VS Code is correctly set for the one you use, eg zsh. For example "terminal.integrated.defaultProfile.osx": "zsh", other resources also mentioned setting "terminal.integrated.shellArgs.osx": [].
To check nvm is working in VS Code, when you open the terminal in VS Code can you do nvm --version? If not, the terminal for VS Code is not correctly set.
Then you need to setup the runtimeVersion as described in
https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_multi-version-support
And the runtimeExecutable to be yarn
Example launch.json
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch via Yarn",
"runtimeExecutable": "yarn",
"runtimeVersion": "16.13.2",
"cwd": "${workspaceFolder}/next",
"runtimeArgs": ["start"],
}

How am I able to create a Restart Config instead of the start config (.vscode)

"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}\\main.js"
}
]
}
This is the config for the launch of the website. Is there a way to make a restart config or script?
i found this source on vscode website and i think its exactly what you want.
first install nodemon on your machine with
npm install -g nodemon
then use this configuration
{
"name": "Launch server.js via nodemon",
"type": "node",
"request": "launch",
"runtimeExecutable": "nodemon",
"program": "${workspaceFolder}/main.js",
"restart": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
Assuming you only do this for local development you can try
bdspen/nodemon_vscode which uses nodemon alternatively in production you can configure nodemon from package.json, in order to restart app when fail etc. Also worth mention Forever here.

What is the proper way to debug an npm script using vscode?

I've got an npm script that I'm trying to debug. I use vscode so I thought I'd create a debug configuration and step through it with the debugger.
My npm script look is:
"scripts": {
...
"dev": "node tasks/runner.js",
}
So I created the following debug config:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"runtimeExecutable": "npm",
"cwd": "${workspaceRoot}",
"runtimeArgs": [
"run", "dev"
],
"port": 5858,
"stopOnEntry": true
}
]
}
And when I fire it the script runs, but vscode is never able to connect and I get the error:
Cannot connect to runtime via 'legacy' protocol; consider using 'inspector' protocol (timeout after 10000 ms).
I tried adding an inspector protocol:
{
"type": "node",
"request": "attach",
"name": "Attach (Inspector Protocol)",
"port": 9229,
"protocol": "inspector"
}
And running the npm script via:
npm run dev --inspect
And this time I get the error:
Ensure Node was launched with --inspect. Cannot connect to runtime process, timeout after 10000 ms - (reason: Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9229).
I'm not sure what part I'm missing.
Edit per duplicate tag
I see the other question re: debugging an npm script via vscode, but the details in the other question and answers aren't as detailed and specific. If someone is searching for the specific vscode error messages I ran into or the config type I had they wouldn't necessarily get the level answer detail that this question's chosen answer gives.
You shouldn't try to debug the npm script because what you really want is to attach your debugger to the script that is launched with npm run command (NPM here is used only as a task runner).
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceRoot}/tasks/runner.js"
}
]
}
If you really want to run it using npm script, then you can use the following configuration:
{
"type": "node",
"request": "launch",
"name": "Launch via NPM",
"runtimeExecutable": "npm",
"windows": {
"runtimeExecutable": "npm.cmd"
},
"runtimeArgs": [
"run-script",
"dev"
],
"port": 5858
}
but you also have to change your script command (specify a debug port)
"scripts": {
"dev": "node --nolazy --debug-brk=5858 tasks/runner.js"
},
You can explore various debug configurations simply by clicking the gear icon and selecting one.
More about Node.js debugging can be found in the VS Code documentation.

vscode debug ES6 application

I have VSCode 0.5.0. I set the compilerOptions flag to "ES6" and the editor started recognizing my ES6 code as correct.
I have babel installed.
My Mocha tests use the babel compilers and my tests pass.
My app runs from the command line with no problems when I launch it with babel-node .
When I debug the app from within VSCode, it starts up without the ES6 support, and the app fails for ES6 syntax issues.
Are there debug settings that I missed turning on?
Here's how to get VSCode debugger to work with Babel 6+:
First install dependencies locally:
$ npm install babel-cli --save
$ npm install babel-preset-es2015 --save
Then run babel-node:
$ node_modules/babel-cli/bin/babel-node.js --inspect --presets es2015 -- server.js --inspect
By default, the debugger will listen on port 5858, so make sure the port matches in launch.json for Attach configuration:
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 5858
}
Now attach the debugger in VSCode:
make sure debug configuration is set to Attach and not Launch
run with F5
Nodemon
Although not required, if you also want to use nodemon to pickup code changes without restarting the server, you can do this:
Make sure nodemon is installed:
$ npm install nodemon --save-dev
Run the server
$ node_modules/.bin/nodemon node_modules/babel-cli/bin/babel-node.js --inspect --presets es2015 -- server.js --inspect
Finally, attach the debugger as shown above.
Assuming you have babel-cli installed as a local module in your project the following should work.
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/node_modules/babel-cli/bin/babel-node.js",
"stopOnEntry": false,
"args": [
"${workspaceRoot}/server.js"
],
...
You can try babel-register (you'll also need other companion babel modules as req'd):
npm install --save-dev babel-register
with a launch.json configuration along these lines:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/src/index.js",
"stopOnEntry": false,
"args": [],
"cwd": "${workspaceRoot}",
"preLaunchTask": null,
"runtimeExecutable": null,
"runtimeArgs": [
"--nolazy",
"--require",
"babel-register"
],
"env": {
"NODE_ENV": "development"
},
"console": "internalConsole",
"sourceMaps": true,
"outFiles": [
]
},
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 5858,
"address": "localhost",
"restart": false,
"sourceMaps": false,
"outFiles": [],
"localRoot": "${workspaceRoot}",
"remoteRoot": null
},
{
"name": "Attach to Process",
"type": "node",
"request": "attach",
"processId": "${command.PickProcess}",
"port": 5858,
"sourceMaps": false,
"outFiles": []
}
]
}
This is loosely based on vscode-debug-nodejs-es6 with the addition of the babel-register runtime argument.
By default VSCode launches node just with a --debug-brk option. This is not enough to enable ES6 support. If you can find out what options 'babel-node' passes to node, you could specify the same options in the VSCode launch config (through the runtimeArgs attribute). But this does not solve the issue that babel-node transpiles your ES6 code before running it.
Alternatively you could try to set the 'runtimeExecutable' in your launch config to 'babel-node'. This approach works with other node wrappers, but I haven't verified that is works with babel-node.
A third option (which should work) is to use the attach mode of VSCode: for this launch babel-node from the command line with the '--debug' option. It should print a port number. Then create an 'attach' launch config in VSCode with that port.
babel + nodemon
In the VS Code Terminal, launch your server with the --inspect argument:
nodemon --inspect --watch src --exec node_modules/.bin/babel-node --presets react,es2015 src/server.js
Among the other lines, one will show the port on which the debugger is listening:
...
Debugger listening on port 9229
...
Create the following debug configuration:
{
"type": "node",
"request": "attach",
"name": "Attach to Port",
"address": "localhost",
"port": 9229
}
Launch the debugger, and if everything went fine you will see in the output Terminal:
Debugger attached.
From now on, you can debug your application.
There are two ways of doing it:
First Option using npm command prompt
In package.json file create build command that will execute babel
{
"scripts": {
"build": "babel src --out-dir dist --watch --source-maps"
},
"devDependencies": {
"babel-cli": "^6.23.0",
"babel-preset-es2015-node6": "^0.4.0",
"eslint": "^3.16.0"
}
}
In launch.json Enter following code:
{
"configurations": [
{
"name": "Launch",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/src/index.js",
"stopOnEntry": false,
"args": [],
"cwd": "${workspaceRoot}",
"runtimeArgs": [
"--nolazy"
],
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/dist/**/*.js"
]
}
]
}
Open your cmd window, navigate to your package.json file and execute:
npm run build
Open your VS Code and run your code. It will run and it will stop at all your breakpoints. The reason it works because source maps are generated and VS knows how to map them to your code.
Second option using VS Code task:
In VS Code add following task (Ctrl + Shift + P) and type 'Tasks: Configure Task Runner':
Add following code to tasks.json file
{
"version": "0.1.0",
"command": "${workspaceRoot}/node_modules/.bin/babel",
"isShellCommand": true,
"tasks": [
{
"taskName": "watch",
"args": [
"src",
"--out-dir",
"dist",
"--watch",
"--source-maps"
],
"suppressTaskName": true,
"isBuildCommand": true
}
]
}
Now execute task, but pressing Ctrl + Shift + B (build command) and now you can run and debug your code. VS Code doing the same as what npm is doing in step one.
You will also need to configure babel in .babelrc (located in the root of the project) file like this:
{
"presets": [
"es2015-node6"
]
}
and jsconfig.json (located in the root of the project)
{
"compilerOptions": {
"target": "ES6"
},
"include": [
"src/**/*"
]
}
This is my configuration and it works great! I am using the VSCode debugging, mocha 6.1.4, node: v8.16.0, and Babel version 6.
Make sure to load babel-register and babel-polyfill in runtimeArgs, or else you will get regeneratorRuntime is not defined!
{
"type": "node",
"request": "launch",
"name": "Mocha test debug",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/mocha",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"protocol": "inspector",
"stopOnEntry": false,
"runtimeArgs": [
"--nolazy",
"--require",
"babel-register",
"--require",
"babel-polyfill",
"tests/*.js"
],
"sourceMaps": true
}
babel-node & vs code attach
config a npm script in package.json:
"scripts": {
"debug": "babel-node --debug-brk demo.js --presets es2015,stage-2"
}
add vs code debug configuration:
{
"name": "Attach",
"type": "node",
"protocol": "legacy",
"request": "attach",
"port": 5858
}
When transpiling with bael-node, you should add "--inspect-brk" in the script, so that the script may break when a breakpoint is hit.
Ex:
"start": "babel-node --inspect-brk app.js --presets es2015,stage-2"
Now when you run using npm run start, debugger will be launched and you can see following in your console:
Debugger listening on ws://127.0.0.1:9229/cf72a33c-ab38-4798-be5e-8b8df072f724
For help see https://nodejs.org/en/docs/inspector
That shows debugging process has started and we can attach to it on port# 9229.
Now, you need to add the following debugger config for vs-code to attach to this process: (in launch.json)
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to Process",
"type": "node",
"request": "attach",
"port": 9229
}
]
}
After saving, click the "start debugging" button, to attach to process initiated by node earlier. You may read more about this here

Mocha breakpoints using Visual Studio Code

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.
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:
{
"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).
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.
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.
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.
Go to Debug > Add Configuration... menu
Select Node.js environment
Select Mocha Tests option from the appeared drop-down list
Type the path of your test file as the last item of the args property
Add a breakpoint
Click on Debug icon
Select Mocha Tests as a configuration
Press Start debugging button
:-)
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.
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:
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;
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.
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"
}
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.
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"
},
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
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"
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"
}
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');};
In VSCode version 1.13.0 (macOS), they have it built-in under configurations -> Mocha Tests.
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.
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"
]
}
]
}
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
Stick breakpoints in index.ts any other imported typescript file
Open a terminal and run : mocha --debug-brk ./build/test/appTests.js
From VSC, run the 'Attach' launch configuration
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.
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.
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"
],
}
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.

Resources