Running tests with Karma

If you’ve gone through the Getting started and Loading your code tutorials, this article will show you how to run your tests using Karma.

First, install karma from npm:

$ npm install karma

Then add the following config to example/karma.js. This tells Karma to load jstest.js then use your runner.js script to dynamically load your code and tests. We set ROOT = http://localhost:4180 to make runner.js load files from a static file server we’ll set up in a minute.

// example/karma.js

ROOT = 'http://localhost:4180'

if (typeof window === 'undefined') {
  module.exports = function(config) {
    config.set({
      autoWatch: true,
      basePath:  '..',
      files: [
        ROOT + '/example/karma.js',
        ROOT + '/build/jstest.js',
        ROOT + '/example/runner.js'
      ]
    })
  }
} else {
  __karma__.start = function() {}
}

jstest will detect Karma and automatically use the right reporter for it.

You need to start a static file server that Karma can load your project from:

$ python -m SimpleHTTPServer 4180
Serving HTTP on 0.0.0.0 port 4180 ...

Now, start the Karma server:

$ ./node_modules/.bin/karma start example/karma.js
INFO [karma]: Karma server started at http://localhost:9876/

And open http://localhost:9876/ in your browser. You should see this page:

Finally, run the karma run command to run your tests in all the connected browsers:

$ ./node_modules/.bin/karma run
Chrome 27.0 (Mac): Executed 2 of 2 SUCCESS (0.61 secs / 0.009 secs)