Testing with Jasmine + Karma

By: Sheldon Fernandes | October 26, 2015

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() {


var MainController,

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.

This post has been viewed 2,145 times

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>