Unit testing plays an important role during development work. But there is a misconception about unit testing. Usually developers argue that
Their application is small and it does not need tests, right?
I would say Wrong! A small application can have bugs and it’s bad practice to develop an application without being tested. The other misconception is usually developers say they test their application directly on production environment. After above two statements you can understand the importance of testing. Let’s start by understanding what Karma is and how you can test your code snippet with it.
About Karma
A simple tool that allows you to execute javascript code.The main purpose of Karma is to make your TDD development easy, fast and fun. I used karma version 0.12.28 in this blog.
Installing Karma and other items
For installing karma in your system, follow the steps mentioned here. Apart from karma, we need several other items as well to execute tests.
Jasmine Framework
npm install karma-jasmine --save-dev
Coverage Plugin
npm install karma-coverage --save-dev
PhantomJS Browser
Configuration
In order to test our javascript code, Karma needs to know about our project in order to test it and this is done via a configuration file “karma.conf.js”.
karma.conf.js is located under “<project_name>/src/main/webapp/<folder-name>/karma.conf.js”
Various configuration parameters of karma.conf.js
BasePath
Base path, that will be used to resolve all relative paths defined in files and exclude. If basePath is a relative path, it will be resolved to the __dirname of the configuration file.
Frameworks
Frameworks parameter is used to define testing framework. There are many testing frameworks are available like Jasmine, Mocha, QUnit etc.
Files
List of files/patterns to load while executing test cases.
Browsers
A list of browsers to launch and capture. When Karma starts up, it will also start up each browser which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. You can capture any browser manually just by opening the browser and visiting the URL where the Karma web server is listening.
Possible values are Chrome, Firefox, Opera, Internet Explorer, PhantomJS.
There are other multiple parameters used for configuring karma. You can find more details/explanation about each parameter from here.
Here is sample karma conf file :
// Karma configuration
module.exports = function(config) {
config.set({
// base path used to resolve all patterns (e.g. files, exclude)
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'<folder_name>/angular/angular.js',
'<folder_name>/angular-mocks/angular-mocks.js',
'src/*.js',
'test/*.mocha.js'
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
preprocessors: {
'src/*.js': ['coverage']
},
coverageReporter: {
type: 'text-summary',
dir: 'coverage/'
},
// test results reporter to use
reporters: ['progress', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests on file changes
autoWatch: true,
// start these browsers
browsers: ['PhantomJS'],
plugins : [
'karma-coverage',
'karma-jasmine',
'karma-phantomjs-launcher'
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
Basic example of AngularJS application :
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', function($scope) {
$scope.message = 'Hello World';
}]);
Writing a test case :
describe('MyController Test Example', function() { beforeEach(module('myApp')); var MyControllerObj, scope; beforeEach(inject(function ($rootScope, $controller) { scope = $rootScope.$new(); MyControllerObj = $controller('MyController', { $scope: scope }); })); it('should says hello world', function () { expect(scope.message).toEqual("Hello world"); }); });
We use the describe function to group our tests together.
Each individual test is defined within a call to the it function.
Executing test
To run karma unit test navigate to karma.conf.js and fire below command
karma start karma.conf.js
You can continue to explore more about the Angular JS by checking out our Angular Development Services.