Debugging Facebook’s Jest for React in Visual Studio Code
--
If you’re like me, you have seriously lost some hair trying to get Jest debugging to work (in VS Code or otherwise). I mean, console.log
is great and all, but it really kinda sucks, especially when you could be using this awesome debugger.
I kid you not, in the last eight months or so, I’ve had debugging break on me at least three times. Maybe it’s Jest, maybe it’s VS Code, maybe it’s Node, maybe it’s Babel, maybe it’s TypeScript, maybe it’s all of them or some of them at different times, but keeping debugging working is a part-time job.
And there’s surprisingly little info out there, and most of the info that I found, at least, didn’t work for me. So after my latest round of hair pulling, I figured I’d share my results. Turns out, it seems like perhaps the tooling is finally maturing a bit such that things work with less coercing.
Without further ado, here’s my current config:
You should be able to copy that whole thing and paste it as a new config in your launch.json
file. Obviously, you need to have Jest installed. :)
Worth noting, here’s some relevant config in package.json
:
"jest": "~21",
"jest-cli": "~21",
"ts-jest": "~21", // if you are using TypeScript
"@types/jest": "^20.0.1",
"babel-jest": "~20", // if you be using it
"babel-plugin-transform-amd-to-commonjs": "^0.2.2", // if using amd
"typescript": "2.5.2" // just FYI
Possibly relevant Jest config (with some redacted ;) ):
"jest": {
"moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json"],
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"globals": {
"ts-jest": {
"useBabelrc": true
}
},
"testRegex": "(ts|tsx|js)$"
},
Supposedly, Jest makes testing so much better. My experience is that it feels like a house of cards, but then, that’s front-end development in general. LOL
As always, YMMV. Feel free to comment with other configs that work for you! I will try to keep posting this as things change.
P.S. For reference:
- VS Code Node Debugging
- Jest CLI Options
- Testing TypeScript on Jest
- Transforming AMD to CommonJS Modules — if you get something like
define is not defined
, it may be that you still have some RequireJS modules. This plugin can help make Jest happy with that.