Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Debug TypeScript Unit Test with Jest and VsCode

Posted on: 2017-12-12

If you are using create-react-app or the TypeScript equivalent react-script-ts for TypeScript, you see that the default testing framework is Jest. This is developed by Facebook like React and Redux. Jest procures many advantages like being fast. It doesn't need to load a browser headless or being in a browser at all. It is also fast because it can run the unit tests on a changed test or run the unit test that has a relation to the code changed instead of running every test. In this article, I'll guide you to setup Visual Studio Code to be able to debug directly in TypeScript. I take the time to write something because information on Internet is very slim and the configuration is fragile.

As mentioned, configuring Visual Studio with Jest require subtle detail that can break the whole experience. For example, using Node 8.1.4 won't work, using Node 8.4 or 8.6 works. Another sensitive area is the configuration of Visual Studio. It requires having some specific configurations which vary. The following code is two different launchers that work with Visual Studio Code.

{ 
  "type": "node", 
  "request": "launch", 
  "name": "Jest 1", 
  "program": "${workspaceRoot}/node_modules/jest/bin/jest", 
  "args": [ "-i" ], 
  "preLaunchTask": "tsc: build - tsconfig.json", 
  "internalConsoleOptions": "openOnSessionStart", 
  "console": "integratedTerminal", 
  "outFiles": [ "${workspaceRoot}/build/dist/**/*" ], 
  "envFile": "${workspaceRoot}/.env" 
}

// OR

{ 
  "name": "Jest 3", 
  "type": "node", 
  "request": "launch", 
  "program": "${workspaceRoot}/node_modules/jest-cli/bin/jest.js", 
  "stopOnEntry": false, "args": [ "--runInBand" ], 
  "cwd": "${workspaceRoot}", 
  "preLaunchTask": null, 
  "runtimeExecutable": null, 
  "runtimeArgs": [ "--nolazy" ], 
  "env": { "NODE_ENV": "test" }, 
  "console": "integratedTerminal", 
  "sourceMaps": true
} 

The second one requires to have jest-cli, the first one not. To download the jest-cli use NPM.

 npm install --save-dev jest-cli 

From there you can run directly inside Visual Studio Code under the debug tab the debug program or hit F5.