Karma cheatsheet

What is Karma?

Test in different web browsers (and simulates different devices)

Install

1
npm install -g karma
  • Default packages
    • karma-chrome-launcher
    • karma-coverage
    • karma-jasmine
  • Optional packages
    • karma-firefox-launcher
    • karma-ie-launcher
    • PhantomJS (headless)

Configuration

  • karma init starts the default configuration
  • The config.json file contains:
    • Frameworks: deifne the framework to use: Jasmine
    • Plugins: list of plugins to load
    • Browsers: specify the webbrowser, you need the dependency installed
    • Files: Object or String arrays, with the paths of the test files

How does it work

  1. Start the web server
  2. Start the browsers, with the server address
  3. Try to capture the browser session in each one of them
  4. We can repeat tests or release the session and close the browser

Reports

  • The results can be configured in the reporters key of the config.json
    • progress
    • html
    • coverage: report in Icoov + HTML via karma-coverage plugin

Example configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//example of RequireJS configuration
var tests = [];
for (var file in window.__karma__.files.hasOwnProperty(file)){
if(/.*specs\.js$/.test(file)){
tests.push(file);
}
}

requirejs.config({
//karma serves files from `base`
baseUrl: '/base/src/.tmp/merge/js',
paths:{
'jasmine-jquery': '/base/src/test/lib/required/jasmine-jquery',
'polyfill': 'core/polyfill-launcher',
'jquery': 'vendor/jquery'
},
shim:{
jquery: {
exports: '$'
}
},
//ask Require.js to load these files (all our tests)
deps: tests,
// starts test run, once Require.js is done
callback: window.__karma__.start
});