Sometimes, debugging with console.log
is not enough to find out what is
happening in the code, as console.log
prints only plain objects but neither
functions nor objects with circular references. Besides, it's possible you
may need to know the context and flow of the code.
Read more about debugging with VS Code in VS Code: Debugging.
The VS Code editor has built-in debugging support for the Node.js runtime
and can debug any language transpiled into JavaScript. To configure the
debugger, open the launch.json
file located in your workspace's .vscode
folder and add the following:
{
"version": "1.0.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest: current file",
//"env": { "NODE_ENV": "test" },
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["${fileBasenameNoExtension}", "--config", "jest.config.js"],
"console": "integratedTerminal",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
}
]
}
Read more details about Debugging in VS Code and Node.js debugging in VS Code.
- Open the unit test file you want to debug.
- Set breakpoints or the
debugger
statement where you want to stop. - Press
Ctrl + Shift + D
, or click on the Debug icon in the left panel. - Select DEBUG ‣ Jest: current file option in the top panel.
- Press
F5
to start debugging.
See more recipes debugging Jest in vscode-recipes/debugging-jest-tests.
As Jest is running under a Node environment, we can use its built-in debugger to inspect our code. So we can open a process to run Jest and allow an external debugger can connect to:
node --inspect-brk <node-args> <jest-cli-path> <jest-args>
If you have installed jest-cli
in package.json
, the command to run can be as follow:
node --nolazy --inspect-brk ./node_modules/jest-cli/bin/jest.js --runInBand --colors --verbose <path/to/file>
Or if you have installed jest, just change the path of the Jest executable:
node --nolazy --inspect-brk ./node_modules/jest/bin/jest.js --runInBand --colors --verbose <path/to/file>
See more details about the arguments used in the previous command: cli options.
We can register in package.json
the previous command so that we can run Jest debugger as a npm script:
"jest:debug": "node --nolazy --inspect-brk ./node_modules/jest/bin/jest.js --runInBand --colors --verbose"
To debug in Google Chrome (or any Chromium-based browser), simply open your browser and follow the instructions below:
- Place the
debugger
statement in any of your test files. - Run the command:
npm run jest:debug path/to/file
- Type
chrome://inspect
on any Chromium-based browser.- Click on Open Dedicated DevTools for Node...
- Or select one of the Remote Target options you can connect to.
You should see the Chrome DevTools
start, and that code execution
is paused at the start of the executable jest.js
, so you should
click on ‣ Resume script execution button (looks like a "play").
Read more details about Jest Troubleshooting.
Amazing! Thanks.