Understanding Karma

Initially i thought karma helps to write unit-test cases..no its wrong..its only a test case runner where we can see some results/reports of unit test cases… 🙂



Everything else need for writing unit-test case is jasmine alone.

Anyways as we are trying to understand karma..lets go to the point…

npm install --save-dev karma //allows you to install karma in your local project

If we’re using the yeoman generator with our apps, this is already set up for us. Just you have to run

karma init

To kick it off, we’ll use the karma init command which will generate the initial template that we’ll use to build our tests:

$ karma init karma.conf.js

It will ask us a series of questions and when it’s done, it will create a configuration file.

When it’s done, it will create a file in the same directory where we ran the generator that looks similar to the following:

// Karma configuration
module.exports = function(config) {
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
//plugins required to generate report
plugins: [
 'karma-coverage', //this we used to generate report

//this is the directory where you can check the results/reports
coverageReporter: {
 type: 'html',
 dir: 'coverage/'

 junitReporter: {
 outputFile: 'test-results.xml',
 suite: ''

 preprocessors: {
 // source files, that you wanna generate coverage for
 // do not include tests or libraries
 // (these files will be instrumented by Istanbul)
 // 'src/*.js': ['coverage']
 'app/**/!(_test).js': ['coverage']

// test results reporter to use
reporters: ['progress', 'junit', 'coverage']  ,
// enable / disable colors in the output (reporters and logs)
    colors: true,
// level of logging
    logLevel: config.LOG_INFO,


Now that we have our karma.conf.js file generated, we can kick off karma by issuing the following command:

$ karma start karma.conf.js

With this you can see files that are generated in coverage folder in your project directory. Run index.html in coverage folder to see the report. Thats it 🙂
Links to refer: