Connect Jasmine, Karma, and Webpack to VS Code

If you’d like to learn how to run and debug Jasmine tests executed using the Karma test runner, right from VS Code, you’ve come to the right place.

Check out the repository referenced in this post at: mikfreedman/jasmine-webpack-vscode

Installation

Install VSCode

brew cask install visual-studio-code

Install Angular/Karma Test Explorer for Visual Studio Code

Install Node Packages

npm install

Test For Great Success

Use the “Test Explorer” in VS Code to run / debug tests

Break right into your code, with variable names and everything!

How it works

Using the Angular/Karma Test Explorer extension, you can attach to the Chrome instance that’s running your Karma tests. The following configuration makes this work: karma.conf.js, .vscode/settings.json. The repo contains step by step diffs in its git log, I’ve detailed some key points below.

Attaching the debugger

The Angular/Karma Test Explorer expects you to setup karma to execute chrome to listen for debugger connections on port 9222. Here’s what the extension’s default launch.json looks like:

    "angularKarmaTestExplorer.debuggerConfiguration": {
        "name": "Debug tests",
        "type": "chrome",
        "request": "attach",
        "port": 9222,
        "sourceMaps": true,
        "webRoot": "${workspaceRoot}",
        "sourceMapPathOverrides": {
            "webpack:/*": "${webRoot}/*",
            "/./*": "${webRoot}/*",
            "/src/*": "${webRoot}/*",
            "/*": "*",
            "/./~/*": "${webRoot}/node_modules/*"
        }
    }

So we need to setup our karma.config.js to allow for this connection:

-      browsers: ['ChromeHeadless'/*,'PhantomJS','Firefox','Edge','ChromeCanary','Opera','IE','Safari'*/],
+      browsers: ['ChromeHeadlessDebugging'/*,'PhantomJS','Firefox','Edge','ChromeCanary','Opera','IE','Safari'*/],
+      customLaunchers: {
+        ChromeHeadlessDebugging: {
+          base: 'ChromeHeadless',
+          flags: [
+            '--remote-debugging-port=9222'
+          ]
+        }
+      },

Confirm this works by looking at the extension logs and seeing something like this:

[3:24:25 PM] INFO: Listening to AngularReporter events on port 9222
[3:24:33 PM] INFO: Test loading completed

Mapping Source

Get webpack to emit inline source maps in karma.conf.js. Also ask it nicely to not minimize the generated code so that variable names match.

       webpack: {
+        devtool: "inline-source-map",
+        optimization: {
+          minimize: false
+        },

Kill stray stuff

Keep an eye out for errant Chrome instances that gum up the works and generally foster weird behavior.

ps -ef | grep 9222 | cut -f 5 -d ' ' | xargs kill

Check out what this does