JavaScript unit testing tutorial using Jasmine

This post will teach you to write JavaScript unit tests using Jasmine in under 60 minutes. This tutorial is aimed at absolute beginners. Team Qxf2 member, Rupesh Mishra, is learning to write unit tests in different languages. He is sharing his learning here in the hope that more testers get started with unit testing. This is one in a series of posts on getting started with unit testing in various languages. The rest of this post is by Rupesh.


Overview

Jasmine is an extremely popular behavior-driven development (BDD) unit testing framework for JavaScript. Jasmine can run on any JavaScript-enabled platform and is easy to read.

At a high level, these are the steps we cover:
1. Install Jasmine
2. Write a JavaScript program to use as the program under test
3. Write the Jasmine unit test
4. Execute the test and view results

1. Install Jasmine
Download Jasmine here. I downloaded the latest version of jasmine-standalone in zip format and unzipped it. For me latest version was jasmine-standalone-2.0.3 .
Now in the jasmine-standalone folder($JASMINE_DIR):

  • /lib  folder contains all the libraries for Jasmine.
  • /spec  folder to write test file.
  • /src  folder to contain Javascript source file,but I can keep my Javascript file any where in my project.
  • SpecRunner.HTML  to execute my test which is already created in spec folder and it will take the path of my source Javascript file .

I emptied the /spec folder. I also deleted the /src folder. These two folders had examples and I did not need them.

2. Write a JavaScript program
To write my JavaScript program, I created a JavaScript project JasmineUnitTesting in Eclipse and added a new file with name ExampleCode.js .

function AddTwoNumbers(a,b) {
  return a + b; //Function to return addition of two numbers a and b.
}
 
function MultiplyTwoNumbers(a,b) {
	  return a * b; //Function to return product of two numbers a and b.
}

I have created two simple programs for addition and product of two numbers in ExampleCode.js .

3. Write the Jasmine unit test
Before I wrote my test program, I added the jasmine-standalone-2.0.3 folder to my project by doing simple copy-paste of folder. I can also do it by using Import option in Eclipse. I then added a new file UnitTest.js in the $JASMINE_DIR/spec folder.
My project files structure looks like this.

jasmineProject

Jasmine tests consists of two parts primarily:
1. describe blocks to describes a suite of tests
2. it blocks for individual test specification

Both the describe and it functions take two parameters
1. A text string to explain the purpose of our test (e.g.: test name)
2. function()

Here is my complete UnitTest.js. In this program I am testing my functions written in ExampleCode.js.

describe("Testing Two Numbers", function() {
	var a = 4;
	var b = 3;
    it("Add Numbers", function() {
        expect(AddTwoNumbers(a,b)).toEqual(7);
    });
    it("Multiply Numbers", function() {
        expect(MultiplyTwoNumbers(a,b)).toEqual(12);
    });
 
    it("Compare Numbers to be Greater Than", function() {
    	expect(a).toBeGreaterThan(b);
    });
 
    it("Compare Numbers to be Less Than", function() {
    	expect(b).toBeLessThan(a);
    });
});

The methods toEqual, toBeLessThan, toBeGreater are known as matchers – assert methods that increase the readability of code. In Jasmine each matcher implements a Boolean comparison between the actual value and expected value. It is responsible for reporting to Jasmine if the expectation is True or False. Jasmine will then pass or fail the Spec.
Here is the list of some popular matchers in Jasmine:-

  1. expect(a).toBe(b);
  2. expect(a).not.toBe(b);
  3. expect(a).toMatch(b);
  4. expect(a).toBeDefined();
  5. expect(a).toBeNull();
  6. expect(a).toContain(“value”);
  7. expect(a).toBeLessThan(b);
  8. expect(a).toBeTruthy();
  9. expect(a).toBeFalsy();
  10. expect(a).not.toBeNull();

4. Execute the test and view results
To execute this test I have to run $JASMINE_DIR/SpecRunner.html. But before that, lets update the source file and spec file location.

 
<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Jasmine Spec Runner v2.0.3</title>
 
  <link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.3/jasmine_favicon.png">
  <link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.3/jasmine.css">
 
  <script type="text/javascript" src="lib/jasmine-2.0.3/jasmine.js"></script>
  <script type="text/javascript" src="lib/jasmine-2.0.3/jasmine-html.js"></script>
  <script type="text/javascript" src="lib/jasmine-2.0.3/boot.js"></script>
 
  <!-- include source files here... -->
  <script type="text/javascript" src="../ExampleCode.js"></script>
 
  <!-- include spec files here... -->
  <script type="text/javascript" src="spec/UnitTest.js"></script>
 
</head>
 
<body>
</body>
</html>

In this HTML file, I put the exact files location of my source and spec files.

To view results, I have to open SpecRunner.html with a browser.

result_jasmine_1

I now have information about all the specs and number of failures. I also get the information about jasmine-standalone version and total time taken by Jasmine to finish this test.


References:

Here are some useful references that I used to learn Jasmine.
1. Official Jasmine documentation
2. An excellent (but somewhat advanced) tutorial by Evan Hahn


9 thoughts on “JavaScript unit testing tutorial using Jasmine

  1. I have a clarification, of course i am very naive to writing tests.,,
    My question is that, does the “source files” and the “spec files ” needs to be updated in “SpecRunner.html” each time a new .js file is created? Doesn’t that make the work tedious?
    I suppose , to make things better , “Karma -Javascript Test runner” is to be used?

    Forgive me if i am wrong..

    1. Nishi, yes – you need to use a test runner of your choice (e.g.: Grunt based) that can intelligently auto-detect tests. We wrote this post aimed at rank beginners and did not want to include anything more than the simplest of basics.

  2. Hi, if i want to stop execution of suits on any one test case fails, or if first case fails then i want to stop execution of spec means i do not want remaining test to run. What is the way to achieve that?

  3. Hi if anyone know how to use jasmine j2ee project. Also if I copy the library it’s showing some error. In ci.js This is the error.

    Multiple markers at this line
    – Semi-colon expected
    – Semi-colon expected
    – Semi-colon expected
    – Expected ‘/’ in regular
    expression literal

    But if I install it using npm it won’t show any errors but don’t know where is the library, spec and src folder. We need these folder to place the path for these files in specRunner.html.
    Also I executed successfully in sublime txt. So the problem is not know how to use it in eclipse with j2ee

Leave a Reply

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