VSCode: How to debug current Jest test file - windows

How to launch jest in debug mode on the current opened file, and only this one, regardless of the OS (windows, linux, mac).
The problem:
When using vscode under windows, it is impossible to jest the current (active) file, and only this one.
This debug config (from https://github.com/microsoft/vscode-recipes/tree/master/debugging-jest-tests):
{
"type": "node",
"request": "launch",
"name": "Jest Current File",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": [
"${fileBasenameNoExtension}",
"--config",
"jest.config.js"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
}
}
Will not run only the active test if you have several tests with the same name (like index.test.js)
If I replace
"args": [
"${fileBasenameNoExtension}",
....
]
by
"args": [
"${file}",
...
]
It will not work at all as the first argument jest expects is a regex and ${file} returns the absolute path of the file, which, on a windows machine will contain \ backslashes which in turn will be interpreted as escaping the following chars in the pattern.
After reading carefully Jest's doc, it's impossible to specify a single file.
And VSCode is unable to convert a variable to a regexp.
The solution from this question, although almost similar, will not work either as it fails with files of the same name (case 1).
So either more tests than expected are run, or no test at all is run.
I've found a solution involving a separate script but any other solution would be appreciated.

Taken from here: https://github.com/Lemoncode/jest-vs-code-debugging-example/blob/master/custom-solution-config-package-json/01-implemented/.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest single run all tests",
"program": "${workspaceRoot}/node_modules/jest-cli/bin/jest.js",
"args": [
"--verbose",
"-i",
"--no-cache"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"type": "node",
"request": "launch",
"name": "Jest watch all tests",
"program": "${workspaceRoot}/node_modules/jest-cli/bin/jest.js",
"args": [
"--verbose",
"-i",
"--no-cache",
"--watchAll"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"type": "node",
"request": "launch",
"name": "Jest watch current file",
"program": "${workspaceFolder}/node_modules/jest-cli/bin/jest",
"args": [
"${fileBasename}",
"--verbose",
"-i",
"--no-cache",
"--watchAll"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}

The accepted answer provides launch tasks to run all tests, watch all tests or watch a single file. If you just want to run the tests in the current file then the --testPathPattern option is what you want:
{
"type": "node",
"request": "launch",
"name": "Jest debug current file",
"program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
"args": ["--verbose", "-i", "--no-cache", "--testPathPattern", "${fileBasename}"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
This does have the problem that similarly named files may be run by mistake, as ${fileBasename} is just the filename - it doesn't match the path at all.
On reflection this isn't a terribly good answer. I'm going to leave it up, more as a warning than as something helpful.

I don't think ${relativeFile} will work as it gives the relatvie path that Jest doesn't like either.
Instead, you should use ${fileBasename}
"args": [
...,
"${fileBasename}"
]

The solution mentionned in the above question (involves a separate script):
debug configuration:
{
"type": "node",
"request": "launch",
"name": "Jest Current File",
"program": "${workspaceFolder}/src/utils/betterJestCli.js",
"args": [
"${relativeFile}",
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/src/utils/betterJestCli.js",
},
"cwd": "${workspaceFolder}",
},
betterJestCli.js:
const { exec } = require('child_process');
const path = process.argv[2];
const child = exec(
['"./node_modules/.bin/jest"', path.replace(/\\/g, '/'), '--config', 'jest.config.js'].join(' '),
// eslint-disable-next-line prefer-arrow-callback, func-names
function (error/* , stdout, stderr */) {
if (error) {
// eslint-disable-next-line no-console
console.log(error);
}
}
);
// to see Jest's output
child.stderr.pipe(process.stderr);
So replacing \ by / on a relative path does the trick since / has no meaning from a regex point of view (escaping the . would be a good idea too).
The biggest issue is that I lose Jest's output colors in the terminal.
It's not yet tested under different environment (linux, mac) so I don't know if it's cross env.
Any other ideas?

I am using the following debug config in VSCode to run the current jest file
{
"name": "Debug Current Jest File",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
"args": [
"--runTestsByPath",
"${relativeFileDirname}/${fileBasename}"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"port": 9229
}
Tested it on Windows and WSL (Ubuntu-18), not sure about mac.

Related

lldb not working with VS Code on Mac - outDebug file

I'm new to VS Code. I got debugging with lldb working--for one day it worked great.
Then it began to malfunction, displaying the arrow several source statements away from the actual execution. I've tried several config changes using online guidance to no avail. I thought that maybe the debug database was messed up so I wanted to try to get it to regenerate, so moved the outDebug file aside. That did not cause it to be rebuilt.
I'm running this launch.json configuration:
{
"name": "(lldb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/rmv_ms",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb",
"miDebuggerPath": "/usr/bin/lldb",
"preLaunchTask": "clang build active file"
},
and this in tasks.json:
"tasks": [
{
"label": "clang build active file",
"type": "shell",
"command": "/usr/bin/clang",
"args": [
"-std=c17",
"-stdlib=libc++",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"group": { "kind":"build", "isDefault":true },
"presentation": {
// Reveal the output only if unrecognized errors occur.
"reveal": "silent"
},`enter code here`
// Use the standard MS compiler pattern to detect errors, warnings and infos
"problemMatcher": "$gcc"
}
]
The latest behavior is that when I try to start debug session it displays a menu asking me what to attach to (whatever that means) but I don't even see my program listed.

Visual Studio Code Python Debugger Windows

I seem to be missing something simple, but I can't figure out why I am unable to debug python using Visual Studio Code on Windows. I've tried setting up the debugger as shown by Microsoft, and this youtube video. I've done a clean install of Visual Studio Code (including the python extension) and Python 3.6. I have no other python versions installed. I keep getting the following errors in the Python Debugger:
cd "c:\Users\xxx\Documents\Python Scripts" ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\python.exe" "C:\Users\xxx\.vscode\extensions\ms-python.python-2018.3.1\pythonFiles\PythonTools\visualstudio_py_launcher.py" "c:\Users\xxx\Documents\Python Scripts" 53746 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput "c:\Users\xxx\Documents\Python Scripts\.vscode\launch.json"
-bash: cd: c:\Users\xxx\Documents\Python Scripts: No such file or directory
env: ‘C:\\Users\\xxx\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe’: No such file or directory
It's complaining that it can't find the python.exe file, but it clearly can since VS code indicates that it's attached:
My launch.json file is the default, and I've tried all the configurations:
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}"
},
{
"name": "Python: Attach",
"type": "python",
"request": "attach",
"localRoot": "${workspaceFolder}",
"remoteRoot": "${workspaceFolder}",
"port": 3000,
"secret": "my_secret",
"host": "localhost"
},
{
"name": "Python: Terminal (integrated)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
},
{
"name": "Python: Terminal (external)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "externalTerminal"
},
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": [
"runserver",
"--noreload",
"--nothreading"
],
"debugOptions": [
"RedirectOutput",
"Django"
]
},
{
"name": "Python: Flask (0.11.x or later)",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "${workspaceFolder}/app.py"
},
"args": [
"run",
"--no-debugger",
"--no-reload"
]
},
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "module.name"
},
{
"name": "Python: Pyramid",
"type": "python",
"request": "launch",
"args": [
"${workspaceFolder}/development.ini"
],
"debugOptions": [
"RedirectOutput",
"Pyramid"
]
},
{
"name": "Python: Watson",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/console.py",
"args": [
"dev",
"runserver",
"--noreload=True"
]
},
{
"name": "Python: All debug Options",
"type": "python",
"request": "launch",
"pythonPath": "${config:python.pythonPath}",
"program": "${file}",
"module": "module.name",
"env": {
"VAR1": "1",
"VAR2": "2"
},
"envFile": "${workspaceFolder}/.env",
"args": [
"arg1",
"arg2"
],
"debugOptions": [
"RedirectOutput"
]
}
]
}
Pylinting works fine, and I have not custom user settings in Visual Studio Code that are related to python. I've tried setting the complete file path to python.exe in settings.json but it makes no difference.
Any help is greatly appreciated. Thanks in advance
I had the same problem but finally got out of it after several adjustment to my settings.
make sure all other settings are in place as you've mentioned especially pythonPath in settings.json and also get "python" installed from the "extension" toolbar in VS code.
Simply change your debug configuration from "Python: Scripts" (or any other configuration you've selected previously) to "Python: Terminal(external)" and you are good to go!
I know, is a pain and I'm experiencing the same.
Apparently python.exe is executing correctly. You will keep seeing that banner because "This is necessary to bootstrap the debugger."
At least this is what Microsoft says.

Debug Jest with Electron using VS Code

I can't manage to debug my Jest tests in VS Code when I use Electron. My tests should run with Electron, not with Node (due to the use of native modules).
{
"name": "Jest Unit Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"program": "${workspaceRoot}/node_modules/.bin/jest",
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd"
},
"env": {
"ELECTRON_RUN_AS_NODE": "1",
"NODE_ENV": "test",
"BABEL_DISABLE_CACHE": "1"
},
"args": [
"-i",
"--verbose",
"-c test/config/jest.unit.json"
],
"internalConsoleOptions": "openOnSessionStart"
},
It is based on the usual config used to debug Jest with Node (which works fine), but I can't get it to work with Electron. The Jest command is correct, but the --debug-brk --inspect option added by VSCode seems to mess out with Jest.
I was able to get my config to work based on your question. Thanks!
{
"type": "node",
"request": "launch",
"name": "Debug Current Jest File:Electron",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
"args": [
"--verbose",
"-i",
"--no-cache",
"--testPathPattern",
"${fileBasename}",
"--coverage",
"false"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {
"ELECTRON_RUN_AS_NODE": "true"
}
}

Breakpoints not being hit when debugging Serverless in vscode

None of my breakpoints are active when debugging my serverless based application in VSCode.
launch.json
{
"configurations": [
{
"console": "integratedTerminal",
"cwd": "${workspaceRoot}",
"name": "Debug",
"port": 5858,
"request": "launch",
"runtimeArgs": [
"run-script",
"vscode:debug"
],
"runtimeExecutable": "npm",
"type": "node"
}
],
"version": "0.2.0"
}
My package.json
...
"scripts": {
...
"vscode:debug": "export SLS_DEBUG=* && node --inspect=5858 --debug-brk --nolazy ./node_modules/.bin/serverless invoke local -s local -f customerAlexa -p ./test/requests/FindAgent-First-GoodZip.json"
},
....
When I choose Start Debugging from the menu, all the red breakpoints go grey and the program just executes without stopping on the breakpoints.
I am running Node 6.11.2, Serverless 1.23.0 on a Mac. Thanks all.
Here is my launch.json which allows me to use breakpoints.
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceRoot}/node_modules/.bin/serverless",
"args": [
"offline",
"start",
"--skipCacheInvalidation"
],
"env": {
"NODE_ENV": "development"
}
}
I am using the serverless-offline to run locally. I also am using webpack and babel. The skipCacheInvalidation is for that.
I hope this points you in the right direction.

Breakpoints in TypeScript with mocha and VSCODE

I'm trying to get vscode to launch mocha and stop on breakpoints. When I run the tests manually I use the following command:
$ mocha -r node_modules/reflect-metadata/Reflect.js --recursive
I can also use the following command:
mocha -r node_modules/reflect-metadata/Reflect.js --recursive --debug-brk
And the following debug config:
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to Process",
"type": "node",
"request": "attach",
"processId": "${command.PickProcess}",
"port": 5858,
"sourceMaps": true,
"outFiles": [
"src/**/**.js",
"test/**/**.test.js"
]
}
]
}
This allows me to set breakpoints in the .js files and see the original TypeScript source. But I can't set a break point directly in the TypeScript code.
My second problem is that I would like to simply press debug in the VSCode UI and trigger mocha in debug mode automatically and again hit breakpoints directly in the .ts files.
Is this possible?
I had already a very similar setup as #JasonDent but that didn't work. The node2 setting is already outdated (vscode will warn you). Instead simply add "protocol": "inspector" and voilá breakpoints are hit now:
{
"name": "Mocha",
"type": "node",
"protocol": "inspector",
"request": "launch",
"cwd": "${workspaceRoot}",
"preLaunchTask": "tsc",
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
"args": [ "--no-timeouts", "--colors", "${workspaceRoot}/out/test/**/*.js" ],
"stopOnEntry": false,
"runtimeExecutable": null,
"env": {
"NODE_ENV": "testing"
},
"sourceMaps": true
},
Here's my config based on the latest task building in VSCode. Out the box it doesn't work with Typescript!? Anyway combining the answer from #Jason Dent I was able to get it working! Its also using the newer node2 debugger. For your setup, change the build/test to where ever you have put your files.
{
"type": "node2",
"request": "launch",
// Automatically stop program after launch.
"stopOnEntry": false,
"name": "Mocha Tests",
"cwd": "${workspaceRoot}",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/mocha",
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/mocha.cmd"
},
"runtimeArgs": [
"-u",
"tdd",
"--timeout",
"999999",
"--colors",
"--recursive",
"${workspaceRoot}/build/test"
],
"sourceMaps": true,
"outFiles": ["${workspaceRoot}/build"],
"internalConsoleOptions": "openOnSessionStart",
// Prevents debugger from stepping into this code :)
"skipFiles": [
"node_modules/**/*.js",
"<node_internals>/**/*.js"
]
},
I also recommend a separate launch profile for debugging Mocha tests. I have the following configs, working with Mocha Typescript test.
My launch.json debug mocha profile looks like the following:
{
"type": "node",
"request": "launch",
"name": "Debug tests",
"runtimeExecutable": "mocha",
"windows": {
"runtimeExecutable": "mocha.cmd"
},
"preLaunchTask": "build:tests",
"runtimeArgs": [
"--debug-brk",
"-p",
"tsconfig.test.json",
"test-js/test/index.js"
],
"program": "${workspaceRoot}\\test\\index.ts",
"outFiles": [
"${workspaceRoot}\\test-js\\**\\*.js"
],
"port": 5858
},
build:tests is a vs code task, that runs 'tsc -p tsconfig.test.json'. I had some issues in the past with gulp-typescript sourcemap generation, that's why I'm using TSC at the moment.
My tsconfig.test.json is:
{
"compilerOptions": {
"outDir": "./test-js",
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2016",
"declaration": true,
"sourceMap": true,
"inlineSources": true
},
"files": [
"./test/index.ts"
]
}
I hope you figured it out by now.
Basic answer, yes you can set breakpoints in .ts files and debug them with VSCode. They have a walk through here on general debugging: Debugging with VSCode
The key part is that you need to make a launch profile explicitly for mocha. This is just an example of how I got it to work. You will need to add something like the following to your .vscode/launch.json.
{
// Name of configuration; appears in the launch configuration drop down menu.
"name": "Run mocha",
// Type of configuration. Possible values: "node", "mono".
"type": "node",
// Request type "launch" or "attach"
"request": "launch",
// Workspace relative or absolute path to the program.
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
// Automatically stop program after launch.
"stopOnEntry": false,
// Command line arguments passed to the program (mocha in this case).
"args": ["--recursive", "lib/*.test.js"],
// Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
"cwd": "${workspaceRoot}",
// Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
"runtimeExecutable": null,
"outDir": "${workspaceRoot}/lib",
"sourceMaps": true,
// Environment variables passed to the program.
"env": { "NODE_ENV": "test"}
}
This will launch mocha to test *.test.js files in the lib directory.
I used the following tsconfig.json file and have my unit tests next to the code:
{
"compilerOptions": {
"target": "es5",
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./lib",
"sourceMap": true,
"removeComments": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"data",
"lib"
]
}

Resources