Debug Angular 12 Karma Tests in VSCode

Zak Barbuto
NextFaze
Published in
3 min readSep 30, 2020

Update 2021–10–05: This still works with Angular 12. I changed the launch config slightly and added a note about testing a single file.

Angular does not come with a launch.json for VSCode out of the box. What’s worse, if you do some Googling for “debugging karma tests in VSCode” the results you get are likely quite out of date — intended for very old versions of either Angular or VSCode.

Here’s some minimal changes to a brand new Angular 10 CLI project that will allow you to attach the VSCode debugger to your running Karma tests.

1. Update your karma.conf.js

Highlighting the only parts that need to be added:

browsers: ["ChromeHeadlessNoSandbox"],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: "ChromeHeadless",
flags: [
"--no-sandbox",
"--user-data-dir=/tmp/chrome-test-profile",
"--disable-web-security",
"--remote-debugging-address=0.0.0.0",
"--remote-debugging-port=9222",
],
debug: true,
},
},

The important parts being we are now using headless chrome (since we are using VSCode for our debugging, we don’t need to open a full Chrome instance any more) and we are configuring a remote debugging port.

2. Create a launch.json

If you’re happy to run all your tests through ng test then you really only need the first configuration which connects the debugger to our headless Chrome instance. However, you typically don’t want to run your full test suite when you’re debugging tests in just one file. I like the convenience of being able to just hit F5 and run ng test on my currently open test file, which is what the second configuration is for.

The important parts here are that:

  1. Our port matches the remote-debugging-port in your karma.conf.js
  2. We enable source maps and have the pathMapping set up as above
  3. We use "type": "pwa-chrome" instead of just "chrome" in the latest VSCode so we don’t need the Debugger for Chrome extension. However, if you have that extension installed, feel free to substitute "pwa-chrome" for "chrome" — the rest of the config can remain the same.
  4. "restart": true ensures that the task keeps running even when our tests exit — useful if you are testing files one at a time, for example.

Run your tests and attach

Run your Angular tests however you like — either via ng test in the terminal and then run the “Attach to Karma” configuration or just run the the “Run test file” launch configuration with a spec test file open in the editor (note that the Attach to Karma” task still needs to be running in the background when running “Run test file”).

Play “Attach to Karma” with `npm test` running in the background

You should now be able to set breakpoints and — as your tests re-run when you make changes— VSCode will pause as expected.

That’s it!

Short, sharp and sweet. Hope this helped you out, and have a great rest of your day.

--

--