How to debug Jest tests with VSCode (2021 Version)
One of my most viewed stories was How to debug Jest test with VSCode. This was written back in 2017. Since then there have been much improvements to Jest, VSCode, Typescript that make many of the details about command line parameters obsolete. I wanted to make an updated version which I think is the simplest approach.
(There is video at the bottom if you would rather watch than read)
Steps:
In under 20 steps you can have complete debug setup for you to expand on.
- Make directory for project
mkdir debug-test
- Navigate to directory
cd debug-test
- Initialize NPM
npm init -y
- Configure package entry point and metadata
- Install dependencies
npm i typescript jest @types/jest ts-jest
- Create .gitignore and add ignore locations
- Create tsconfig.json
npx tsc --init
and set options (outDir: `./build`) - Setup package.scripts (build, prestart, start, test, test:debug)
- Create src/index.ts with exported function
- Verify
npm start
compiles and runs index - Create src/index.test.ts using function from index.ts
- Initialize jest config using ts-jest
npx ts-jest config:init
and set ignore locations - Verify
npm test
runs the test - Set breakpoint in the test and start debugging!
The first article spent a bit of time walking through the struggles you might have which could be interesting but if you just want to get to the solution of debugging jest tests I think is the fastest way.
I think some people find the integrated Debug in package.json a bit too magical or are more purist and don’t want a test editor adding this to their package.json.
There is a setting that allows you to disabled it here:
"debug.javascript.codelens.npmScripts": "top"
Video:
In this video I go through each step above and explain the progression.
Code Repo:
https://github.com/mattmazzola/debug-jest
References:
npx tsc --init
https://www.typescriptlang.org/tsconfig#libnpx ts-jest config:init
https://github.com/kulshekhar/ts-jest#getting-started- JavaScript Debug Terminal
https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_javascript-debug-terminal
Conclusion:
I hope this article will allow people to get setup debugging tests faster so they can spend more time on writing the tests and working on the meaningful problems. Let me know what you thought in the comments!