Debugging Jest test project with VS Code (and NX, Angular, Powershell)

With Karma you’d boot up the browser and use its F12/Developer Tools to debug the tests. Jest, being optimized for CLI and specially CI/CD environments, does not come with the same simplified debugging experience. However, you can tap in to VS Code’s debugger for perhaps, even a better toolset. Setting it up on a per project basis does require few manual steps and this post is about a simple Powershell Script that lets you skip even that.

If you googled around, you’ll find that there’s a few references on how to setup VS Code Debugger for Jest in a NX/Angular environment, including one from the NX blog. In essence you need to create a launch.json file in the .vscode folder at the root of your workspace.

In the sample JSON from the blog, you’d see that you have to hard code a few things on to this file:

  1. The project name (since a NX workspace would essentially be mulit-project)
  2. The testNamePattern
  3. The path to the file being debugged.

You’d find that simply replacing testNamePattern with .* and using breakpoints and/or .only suffix on describe/it/test blocks more convenient. And (perhaps due to recent updates to VS Code) you can set --testFile=${file} without hardcoding the path to file being debugged.

This still leaves you update the launch.json file every time you want to switch the project being debugged. This is something we can easily achieve with a Powershell script.

param([string]$relativePath = "")
if ($relativePath -eq $null) {
Write-Error "Specify a file to debug."
exit 1
}
$file = Resolve-Path Path $relativePath
$matches = $file | Select-String Pattern "(?<root>.*\/)(apps|libs)\/(?<prj>.*?)\/src/.*"
if ($matches.Count -eq 0) {
Write-Error "Specified path did not match the expected pattern."
exit 1
}
$root = $matches.Matches[0].Groups["root"].Value
$prj = $matches.Matches[0].Groups["prj"].Value
$launchCode = @{
configurations = @(
@{
name = "debug-jest-lib"
type = "node"
request = "launch"
program = "`${workspaceFolder}/node_modules/@angular/cli/bin/ng"
args = @(
"test",
$prj,
"–codeCoverage=false",
"–testNamePattern=.*",
"–testFile=`${file}"
)
cwd = "`${workspaceFolder}"
console = "internalConsole"
}
)
} | ConvertTo-Json Depth 3
$outpath = "$root/.vscode/launch.json"
[IO.File]::WriteAllText($outpath, $launchCode, [System.Text.Encoding]::UTF8)
Write-Host "Updated: $outpath"
Write-Host $launchCode
view raw jestdbg.ps1 hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.