UI Development

Getting Started with Automated Unit Testing for Web

Unit Testing is a considerable and basic practice step in the software testing process where individual units or components of a software are tested. In this article, we will mainly focus on how we can automate this task with the use of different unit testing tools. I know what you are thinking, don’t worry I will answer that first.

What exactly Is Automated Unit Testing?

The entire application or system is divided into several testable units to check its source code. A developer can write a section of code in the application just to test the functions, procedures or methods.

UnitTest Frameworks are generally used by the coder to develop automated test cases. The developer codes criteria into the test by using an automation framework, to verify the correctness of the code. During the execution of the test cases, the framework logs failing test cases. Many frameworks will also automatically report and flag, in summary, these failed test cases. The framework may halt subsequent testing depending on the severity of a failure.

Several benefits of Unit Testing:

  • Possible to identify problems earlier and help to fix bugs in the development cycle and save costs.
  • The integration of modules becomes easier as well as reduces bug ratio and time consumption.
  • It helps the developers to understand the code base and enables them to make changes quickly without reflecting on other modules.
  • Automated Unit tests help with code re-use. Migrate both your tests and your code to your new project.

Challenges faced with Unit Testing:

  • The trouble with Test Names is common.
  • Writing wrong test types is also an issue.
  • Understanding the entire code is one of a tedious task.
  • Need to test doubles, as you need both automated and manual unit testing.
  • Lack of proper initial conditions is also a  concern.
  • Finding dependencies is also a tough task.


Some of the best and commonly used Unit Testing Tools

There are various of Unit Testing Tools/Frameworks used to create accurate unit tests. The list is long but for time being we will discuss the topmost tools and how to get started with them.

#1) Karma

Karma is a JavaScript test runner tool created by the AngularJS team. Jasmine is the testing framework, and Karma provides helpful tools that make it easier for us to call our Jasmine tests whilst we are writing code.

Installing Karma

At first, we need to install Node.js:

After this, we need to install the Karma tool via the NPM package manager:

npm install karma --save-dev

If all went fine, the package.json file must have the following contents:

  "devDependencies": {
    "karma": "^0.12.31"

It’s always useful to install the karma-cli if you are on Windows and want to use the Command Prompt since it makes the command karma globally available:

npm install -g karma-cli

Next, is to install karma plug-ins to enable us to use the Jasmine test framework and Google Chrome as the target browser:

npm install karma-jasmine karma-chrome-launcher --save-dev

Now, the package.json contents should have the following:

  "devDependencies": {
    "jasmine-core": "^2.3.4",
    "karma": "^0.12.31",
    "karma-chrome-launcher": "^0.1.12",
    "karma-jasmine": "^0.3.5"

Writing Tests

To create a test, enter the following in the Terminal/Command prompt:

mkdir testFolder
touch testFolder/calculations.controller.test.js

Write the following test code into this new file:

describe('calculations', function () {
  var $controller;
    $controller = _$controller_;
  describe('add', function () {
        it('21 + 2 should equal 23', function () {
            var $scope = {};
            var controller = $controller('CalculationController', { $scope: $scope });
            $scope.x = 1;
            $scope.y = 3;

Configure the Test Runner

We need to create a configuration file for the karma settings before we can run this test. To create this file, enter the following in the Terminal/Command prompt:

karma init karma.conf.js

Enter the following value as the location of your source and test files:


After providing all the inputs, the config file called karma.conf.js will get created in the root folder.

This file can be used to run the tests from the Terminal/Command Prompt with the command:

karma start karma.conf.js

Since we have only a test with no implementation, the test output should look as follows:

> @ test /Users/devuser/repos/CalculatorKarma
> ./node_modules/karma/bin/karma start karma.conf.js
INFO [karma]: Karma v0.11.32 server started at http://localhost:9786/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 42.0.2322 (Mac OS X 10.10.4)]: Connected on socket 2absOkNdcbhgsasaX0fCJ with id 713382556
Chrome 42.0.2322 (Mac OS X 10.10.4) calculation encountered a declaration exception FAILED
    ReferenceError: module is not defined
        at Suite.<anonymous> (/Users/devuser/repos/CalculatorKarma/tests/calculator.controller.test.js:3:13)
        at /Users/devuser/repos/CalculatorKarma/tests/calculator.controller.test.js:1:1
Chrome 42.0.2322 (Mac OS X 10.10.4): Executed 1 of 1 (1 FAILED) ERROR (0.04 secs / 0.005 secs)

We can do a slight optimization by updating the package.json with the script section as follows:

    "scripts": {
    "test": "karma start karma.conf.js"
  "devDependencies": {
    "jasmine-core": "^2.3.4",
    "karma": "^0.12.31",
    "karma-chrome-launcher": "^0.1.12",
    "karma-jasmine": "^0.3.5"

By doing this we can enter the npm test rather than the specific karma configuration detail.

Run the following from the Terminal/Command prompt and it will start the karma process:

npm test

Official Link: Karma

#2) Jasmine

Jasmine is a Javascript Unit Testing framework that starts with behavioral specifications as a basis for writing the test cases.

Jasmine is majorly made up of three functions

  1. describe
  2. it
  3. assertions (expect)

It also has setup method and tear down methods like other standard frameworks,

  • beforeEach() :– Setup Method
  • afterEach() :– Teardown Method

Download the Jasmine

Download the latest version of Jasmine from here. Once it’s downloaded, you can extract and save lib folder in your project.

Create simple Javascript code for Jasmine Test Framework

Let’s write the below Javascript code. Here we have simply declared a person object with few properties and method to get its full name and change Salary:

function Person(first,last,salary,haircolor){
this.firstName = first;
this.lastName = last;
this.salary= age;
this.haircolor= haircolor;
Person.prototype.name = function(){
return this.firstName+ " "+this.lastName;
Person.prototype.changeSalary = function(newSalary){
this.salary= newSalary;
Person.prototype.getSalary = function(){
return this.;

Let’s write a basic test method using the Jasmine Framework.

describe("Test the Person Object", function(){
var p;
p = new Person("Rudraa","Zaat",20000,"Black");
it("Get The Correct Full Name", function(){
expect(p.name()).toEqual("Rudraa Zaat");
it("Confirm if salarychanged",function(){

The above code snippet helps you to understand how we use describe, it and expect methods provided by Jasmine framework.

Now we will create a sample HTML page that will load Jasmine Framework, our Javascript code and Test method to Test the code.

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=2.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Jasmine Demo</title>
<!-- #Test Jasmine Files -->
<link rel="shortcut icon_on" type="image1/png" href="js/lib/jasmine-3.2.1/jasmine_favicon.png">
<link rel="stylesheet" href="js/lib/jasmine-3.2.2/jasmine.css">
<script src="js/lib/jasmine-3.2.1/jasmine.js"></script>
<script src="js/lib/jasmine-3.2.1/jasmine-html.js"></script>
<script src="js/lib/jasmine-3.2.1/boot.js"></script>
<!-- #Test Source Code -->
<script src="js/Person.js"> </script>
<!-- #Test Scripts -->
<script src="js/PersonTest.js"> </script>
<h1>My Jasmine Demo </h1>

Below you can see the output of our example. We don’t see any error as all test passed:

Official Link: Jasmine

#3) Mocha

Mocha is an open-source JavaScript Testing Framework and it runs on Node.js. It provides features like test browser support, coverage report, report test duration, etc. It also contains a JavaScript API for running tests as well as an extensive test interface.

When writing a test in Mocha, there are two basic function calls: describe() and it().

  • In Mocha, we can nest our tests in groups as deep as we deem necessary by simply using describe(). describe() takes two arguments, the first one is the name of the test group, and the second one is a callback function.
describe('string name', function(){
  // We can nest more describe()'s here, or tests here
  •  An individual test case is written in it()it() should be written as if you are describing some test case: “It should not equal zero”, “It should log out the user”, etc. it() accepts two arguments, the first one is the string explaining what the test should do, and the other one is a callback function which contains our actual test:

Install Mocha Globally

You can install Mocha globally by running:

$ npm install -g mocha

Create a project

Now, we will create a project directory named test. Then we’ll create a file named test.js in our test folder. And finally, we’ll initialize our project by running npm init.

When done, you could have a file structure that looks like this:

|-- test1.js
|-- package.json

The following json should present in your package.json file.

"scripts": {
  "test": "mocha"

Once we are done with all of the above, we’re ready to test.

Creating our first test

copy the following in your test.js file:

var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 in case the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(4));

Now use npm test in the command line to run our test  and you should get the following:

    ✓ should return -1 in case the value is not present
1 passing (9ms)


Official Link: Mocha


In the software testing process, automated unit testing is the foundation task. Initially, it was a manual task performed by testers or developers but with the changing needs and time, each and every task in the Software Development Process has become automated. Likewise, the integral part such as Unit Testing also has become an automated task with the use of tools.

About The Author