Testing with Jasmine + Karma

The Setup

AngularJS has many testing frameworks that can be used such as qunit, mocha, protractor, and so on. This particular blog post will be using Jasmine. Jasmine is behavior-driven development framework for testing JavaScript code. Along with Jasmine you will need a Test runner. The well known ones are Karma and Protractor (both by the Angular team). Here we will be using Karma.


Let’s start off by installing Karma. Type the following into the command line.


#This will install Karma
$ npm install karma --save-dev

# This will install the plugin you will need
$ npm install karma-jasmine karma-chrome-launcher --save-dev


For the next step you can used the following guide to set up your karma.conf.js file. Link: Config guide


Creating Test Cases

Once you have Karma setup, we can now start writing test cases for our AngularJS app. Here we have a simple Hello World controller.


angular.module('myApp',[]).controller('MainController', ['$scope', function($scope) {
$scope.greeting = 'Hello TDG!';
}]);


The Jasmine Test case could be written as such


describe(‘Hello TDG ’, function() {

beforeEach(module(‘myApp’));

var MainController,
scope;

beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
MainController = $controller('MainController', {
$scope: scope
});
}));
it('says hello TDG!', function () {
expect(scope.greeting).toEqual("Hello TDG!”);
});

});


Finally, run your test case


karma start karma.conf.js


So what just happened ?


Well, if everything worked out correctly you will see that the test case ran and was successful. The point of the extremely simplified test case and controller was just to get your feet wet. Visit the Jasmine homepage to see what exactly the “describe” and “it” functions actually do and how you can use them to create test cases for your controller.

Write a comment
Cancel Reply