Monday, June 6, 2016

Debug Karma Unit tests using visual Studio code

Debugging JavaScript is not easy, especially outside the browser.
VS Code is so powerful for JavaScript debugger. I managed to get it working under Jasmine/Karma unit tests.

Pre-Requisite

  • Install the karma chrome-launcher to your project
  • Install the vs code chrome debugger extensions

Steps

  1.  Config your kama.conf.js, make sure you can launch chrome with remote-debugging-port 9222
    Add the following in to your karma.conf.js
    1
    2
    3
    4
    5
    6
    customLaunchers: {
          Chrome_with_debugging: {
            base: 'Chrome',
            flags: ['--remote-debugging-port=9222']
          }
     },
  2. Launch the browser custom launcher through gulp task, also we need to disable the JavaScript preprocessors, which purpose is magnifying for the test coverage
    gulp script
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    gulp.task('debug-karma'function (done) {
      new Server({
        configFile: __dirname + '/karma.conf.js',
        browsers: ['Chrome_with_debugging'],
        preprocessors: {
              'components/**/*.js': [],
              'lib/crl/**/*.js' : [],
              'lib/rapidlab/**/*.js' : []
        },
        singleRun: false,
        autoWatch: true,
      }, done).start();
    });
  3. Update launch.json file in the .vscode folder
    launch.json
    {
        "version""0.2.0",
        "configurations": [
            {
                "name""Launch Karma debug page",
                "type""chrome",
                "request""launch",
                "url""http://localhost:9876/debug.html",
                "sourceMaps"false,
                "webRoot""${workspaceRoot}/src/main/webapp"
            },
            {
                "name""Attach without source map",
                "type""chrome",
                "request""attach",
                "port": 9222,
                "sourceMaps"false,
                "webRoot""${workspaceRoot}"
            }
        ]
    }
  4. In the IDE, run task debug-karma, make sure the chrome browser is launched.
  5. Click the Debugger button,select Chrome, choose "Attach without source map", click start button
  6. Refresh chrome browser, or in the debugger console, type 
    location.reload();

Sample Project  

Please check this sample JavaScript project: https://github.com/stevez/KataFizzBuzz/tree/master/javascript
You can import this project to launch the chrome debugger inside your VS Code IDE.

Resources

  1. http://bahmutov.calepin.co/debugging-karma-unit-tests.html
  2. https://github.com/Microsoft/vscode-chrome-debug
  3. https://github.com/karma-runner/karma-chrome-launcher

No comments:

Post a Comment