Unit Testing Using Karma And Jasmine

grunt

This article explains how to run Unit Tests using Karma and Jasmine. This will guideyou to set up Grunt and Karma, configuring it to run Unit tests, writing some sample Jasmine unit tests and an integration test showing the browser differences in action.

Tools and Frameworks used

To run a unit test using Karma and Jasmine, we need following tools/frameworks:

What is Unit Testing?

As stated in the official site of Microsoft “The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect. Each unit is tested separately before integrating them into modules to test the interfaces between modules.” Please visit Microsoft site for more on Unit Testing.

Karma

Karma is a tool made on top of NodeJS to run JavaScript test cases. This is not a testing framework like Jasmine or Mocha or Chai etc. It only allows us to run JavaScript test cases written using testing frameworks like Jasmine.

Karma runs JavaScript test cases against real browsers through Command Line Interface (CLI) rather than virtual browser and DOM. Since, DOM rendering across browsers vary, so for correctness of the test report it uses real browsers. It can be configured what all browsers need to be used while running Karma.

Jasmine

Jasmine is a BDD (Behavior Driven Development) Javascript testing framework provides building blocks to write JavaScript unit test cases. It does not require any other JavaScript Framework. As stated in official documentation of jasmine 2.0.0:

“Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.”

Here is a code snippet which describes basic structure of Jasmine Unit Test Spec:

  1. describe("simple test", function()  
  2. {  
  3. beforeEach(function(){  
  4.   
  5. });  
  6.   
  7. afterEach(function(){  
  8.           
  9. });  
  10.   
  11. it("a is a string", function(){  
  12.           
  13. })  
  14. })  

In the above sample code, there are four key keywords “describe”, “it”, “beforeEach” and “afterEach”. “describe” and “it” functions accept two parameters:

  • a string: This parameter is used to define a string value which explains the purpose of suite.
  • a function: This is a block of code that implements the suite

“describe” is also known as Suite of tests whereas “it” is known as Specs. Similarly, “beforeEach” is known as Setup and “afterEach” is known as Teardown.

As the function name suggests “beforeEach” and “afterEach” functions gets called once before and after each spec (“it” function) respectively within “describe” block. These functions accept a function as parameter.

Installation and Configuration

Before proceeding, make sure NodeJS and Grunt has been installed in your system.

1. Create a project folder. In my case, I have created a project with below folder structure:

project

  • “src” folder is to hold all source codes.
  • “tests” folder is to hold test files.

2. Go to project root folder in command prompt.

3. Run below command to create package.json. This will take through the steps to create package.json. Steps can be skipped by pressing enter on every prompt.

  1. npm init  
4. Run below command to install bower and add dependencies in package.json. It may require to add “sudo” at the beginning of the below command in case of Mac.
  1. npm install bower --save-dev  
5. Run below command to create bower.json. This will also ask few inputs to create bower.json. Steps can be skipped by pressing enter on every prompt.
  1. bower init  
6. Run below commands to install grunt and add dependencies in package.json,
  1. bower install grunt  
  2.   
  3. npm install grunt --save-dev  
7. Install karma and add dependencies in package.json by running below commands in CLI,
  1. bower search karma  
  2.   
  3. bower install karma --save-dev  
  4.   
  5. npm install grunt-karma --save-dev  
8. Create Gruntfile.js 

Create JavaScript file in the project root folder and name it Gruntfile.js. Add below code to create basic structure of the Gruntfile.js to run karma:

  1. module.exports = function (grunt) {  
  2.     grunt.initConfig({  
  3.         pkg: grunt.file.readJSON('package.json'),  
  4.         karma: {  
  5.             unit: {  
  6.                 configFile: "karma.conf.js"  
  7.             }  
  8.         }  
  9.     });  
  10.     grunt.loadNpmTasks('grunt-karma');  
  11.     grunt.registerTask('default', ['karma']);  
  12. };  

9. Create karma.conf.js 

In Gruntfile.js, there is a property “configFile” mentioned for karma object. This is the config file to run karma. Create a JavaScript file in the project root folder, name it as karma.conf.js and add below code:

  1. module.exports = function(config)  
  2.  {  
  3.   config.set({  
  4.     basePath: '',  
  5.     frameworks: ['jasmine'],  
  6.     files: [  
  7.     'tests/**/*Spec.js'  
  8.     ],  
  9.     exclude: [  
  10.     ],  
  11.     preprocessors: {},  
  12.     reporters: ['progress'],  
  13.     port: 9876,  
  14.     colors: true,  
  15.     logLevel: config.LOG_INFO,  
  16.     autoWatch: true,  
  17.     browsers: ['Chrome''Safari'],  
  18.     captureTimeout: 60000,  
  19.     singleRun: false  
  20.   });  
  21. };  
10. Install browser plugins 

In karma.conf.js, I have mentioned “Chrome” and “Safari” as browsers on which test cases to be run. This would require the plugins for both “Chrome” and “Safari” to be installed before running test cases. To install plugins, run below commands synchronously:

  1. npm install karma-chrome-launcher --save-dev  
  2.   
  3. npm install karma-safari-launcher --save-dev  
Create Test files 

Create a “tests” folder in the root project folder and create a JavaScript file inside “tests” folder and name it “BasicSpec.js”. Add below code to the the “BasicSpec.js” file:

  1. describe("simple test", function(){  
  2.   
  3.     beforeEach(function(){  
  4.   
  5.     });  
  6.   
  7.     afterEach(function(){  
  8.           
  9.     });  
  10.   
  11.     it("a is a string", function(){  
  12.         var a = "hello world";  
  13.         expect(a).toBe("hello world");  
  14.     })  
  15.   
  16.     it("b is a number", function(){  
  17.         var b = 1;  
  18.         expect(b).toBe(1);  
  19.     })  
  20. })  

Here I have added very basic test cases. This can be modified based on the application requirement.

Show time

Run “grunt” command in Command Prompt. It will launch “Chrome” browser and “Safari” browser (only if these browsers have already installed in the system). And will show the results in the Command Prompt. It will run all test cases written in any js file inside the tests folder. Each js file name should include “…Spec.js” because the names mentioned in karma.conf.js includes this pattern for spec files.

  1. grunt  
For further reference on Jasmine test-cases, please visit:

Thank you.

Read more articles on Node.js: