Automate Javascript Unit Testing With Karma

Setup Karma for JS Testing

If you are writing tests in javascript you’re awesome!
You are half way on the road to Nirvana when it comes to assuring your code or app behaves as it is supposed to.
In addition to writing tests during develpoment, we, as developers, need to run them and act upon its success or failure. Karma is a cli tool that functions as a test runner that can help us to be more productive during the tests development cycle.

Why Do I Need A Test Runner?

Karma can automate few process in the test driven development workflow. If you’re used to write tests, write the code, and run the tests in the browser so eah time you need to refresh it - chances are it’s not that comfortable and it’s tedious overtime.
Karma can automate the process of refreshing the execution of the tests once a file has changed. But, that’s not all. Karma uses a json configuration object to understand what tasks to run.

// karma.conf.js
var isDebug = process.env.DEBUG || false;
var browsers = [isDebug ? 'Chrome' : 'PhantomJS'];

module.exports = function(config) {
	config.set({
		basePath: '.',
		browsers: browsers,
		frameworks: ['jasmine'],
		files: [
			'node_modules/jquery/dist/jquery.min.js',
			'bower_components/jasmine-jquery/lib/jasmine-jquery.js',

			'src/app.js',
			'src/js/TodoItem.js',
			'src/js/TodoList.js',
			'src/js/ItemView.js',
			'src/js/ListView.js',
			'src/js/filters/Filter.js',
			'src/js/filters/FilterView.js',
			'src/js/filters/FiltersView.js',

			'test/spec/SpecHelper.js',
			'test/**/*.spec.js',
			// 'test/**/*.html',
			// '../tests/mocks/**/*mock.json'
	    ],
	    autoWatch: true,
	    singleRun: false,
        preprocessors: {
        	// 'test/**/*.html': ['html2js']
	        // '../tests/mocks/**/*mock.json': ['json_fixtures']
	    },
	    jsonFixturesPreprocessor: {
	      // strip this from the file path \ fixture name
	      stripPrefix: '.+mocks/',
	      // strip this to the file path \ fixture name
	      // prependPrefix: 'mock/',
	      // change the global fixtures variable name
	      variableName: 'mocks'
	    },
	    plugins : [
	        'karma-phantomjs-launcher',
	        'karma-chrome-launcher',
	        'karma-jasmine',
	        // 'karma-html2js-preprocessor',
	        'karma-spec-reporter',
	        'karma-mocha-reporter'
	        // 'karma-json-fixtures-preprocessor'
	    ],
	    reporters: [
	    	// 'progress', 
	    	// 'dots',
	    	// 'spec'
	    	'mocha'
	    ]
  });
};

Benefits Of Using Karma With Javascript Tests

Karma solves few problems and adds a sense of magic with the configuration approach. Lets overview what a js project can benefit from using karma:

Re-Run Tests

As I mentioned before, I can tell karma to watch (autoWatch: true) for any changes in the files of the app and the specs, and run (singelRun: false) the tests again when I save these changes.

Testing On Multiple Browsers

The browsers instruct karma on which browsers the tests should run. Tests can run on several actual instances of browser or rather a browser engine (such as Phantomjs). In order for that to work properly, there are karam plugins which can launch a browser.

Karma, Mocha, Chai or Any Flavour as A Testing Framework

Karma is testing framework agnostic. With the frameworks property you can tell karma which framework it should load/use in order to run the tests. That also requires a plugin.

Integration with CI

If you’re using a CI server such as Travis, Jenkins, Teamcity or other, you can instruct karma to output the tests results in a relevant format. The reporters array may include several reporters to which karma will print the results of the tests and execution. There are also plugins for that, but sometimes there’s not need to a plugin if the tests results are logged to the console from which it has been executed, i.e Travis-CI cloud service just reads the console output. On the contrary, execution results can be in the format of xml, json or other nice console format like. tests results

Running Karma

Eventually, given karma is installed, in order to tell karma running the tests, the command should be run in the terminal/cmd: karma start path-to-conf-file.

More Goodies!

That’s not all falks!
Karma has a plugin system, so you can find many more plugins which add its valuable solution let it be: loading json files as fixtures, preprocessing files (i.e. html2js) and much more.

In Tikal’s Javascript Testing workshop, we’re using karma in order to run the tests that attendees are writing and changing. The goal is learning to write tests with javascript using jasmine as a testing framework.
In addition, we’re talking about karma and explain in depth the configuration file as well as karma internals.

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com