Unit Testing with Jasmine and Karma

http://justmobiledev.com/wp-content/uploads/2017/11/jasmine-karma.pngUnit Testing with Jasmine and Karma

Background

Ah – unit testing. The ugly, obnoxious step child that always seems to poke his head up at the end of a Sprint cycle when you’re out of time, money and patience. But if you’re reading this blog you know as well as I do that it has to be done.

So I put together a quick 5-step process to get you started with unit testing with Jasime and Karma. Jasmine is an open source unit testing framework and Karma, a test runner that lets you execute code in multiple browsers.

Jasmine supports two new test methodologies called ‘Test-driven Development’ (TDD) and ‘Behavior-driven Development’ (BDD). In short, TDD requires that the development starts by writing an automating test case first. The second step is to write the code supporting the unit tests.
BDD builds expands TDD in the sense that it specifies that unit tests should be defined by the behavior that the business process requires and then provides a structure for user stories that help to describe the behavior.

For the purpose of this tutorial we assume that you have already installed node.js and npm.

Installation

Jasmine

Depending on your development environment Jasmine can be installed as a npm module, ruby gem, python egg, or standalone JavaScript library. In this tutorial we will install it as a node.js module.

You can install Jasmine locally in your project or globally using the npm commands:

1
2
npm install -D jasmine
npm install -g jasmine

You can use the following command to create a spec directory and configuration JSON for your Jasmine project:
jasmine init

Use the spec/support/jasmine.json to include the JavaScript files you would like the Jasmine runner to run.

To start the test run, simply start Jasmine:

1
jasmine

Karma

Karma is also available as node.js package and can be installed using npm package manager:

1
2
3
4
5
6
cd project-dir
// Install Karma
npm install -g karma-cli
// Install browser
npm install karma-jasmine
npm install karma --save-dev

This install karma in the node_modules sub directory.

To run it, use the command below or create a small batch script that executes it:

1
./node_modules/karma/bin/karma start

Some Code to Test

For our test code we are going to solve the Sorites’ Paradox, which has the following premises:

  1. 100 grains of sand are a heap
  2. A heap of sand minus a grain is still a heap

The paradox occurs when Step 2 is repeated and the number of sand grains approaches one.

To solve the paradox we will add a tiny little premises stating that one grain of sand is really not a heap.

The Jasmine Test

A Jasmine test case (test suite) is defined using the ‘describe’ keyword with two parameters: a string and a function. The string is the title for the test and the function is the code to be tested. The function code is split up into code blocks also called a ‘Spec’. A Spec is defined using the keyword ‘it’ and can test multiple expectations which can result in either true or false. A Spec with at least one false expectations results in a failed test. Expectations are build with the ‘expect’ function and combined with ‘Matchers’ that compare the actual value with an expected value.

So let’s implement the Sorites’ Paradox as a unit test. The Spec section below has one expectation which uses the matcher ‘toBeGreaterThan’ in order to determine if the grains of sand still amount to a heap.

Example:

1
2
3
4
5
6
7
describe("Sand Heap", function() {
  var grainsOfSand = 100;
  var heapThreshold = 5;
  it("it is still a heap", function() {
    expect(grainsOfSand).toBeGreaterThan(heapThreshold);
  });
});

Running the Test with Karma

Karma can be configured by running the init function, which creates a Karma configuration file for the test run. Run the following statement from the command line and then follow the script below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
karma init my.conf.js

Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine

Do you want to use Require.js ?
This will add Require.js plug-in.
Press tab to list possible options. Enter to move to the next question.
> no

Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome

What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
>

Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>

Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes

Config file generated at "/your_path/my.conf.js".

Now we need to tell Karma which js files to load: Open the my.conf.js and add the paths to the Jasmine library files and your test case file:

1
2
3
4
5
6
    files: [
      'jasmine-2.2.1/lib/jasmine-core/jasmine.js',
      'jasmine-2.2.1/lib/jasmine-core/jasmine-html.js',
      'jasmine-2.2.1/lib/jasmine-core/boot.js',
      'js/*.js'
    ],

Go to your project directory, create a ‘js’ directory inside and create a file with the Jasmine test case we created in the last section.

Then start karma using the following command:

1
karma start my.conf.js

In case your installation is configured correctly, you should see a browser window open up. The test case will then be executed. At the command prompt you will see that the test case passed.

Now modify your describe statements and set the ‘grainsOfSand’ variable to 5 and rerun Karma. You will see that the Karma output now shows a failed test case for the expectation that failed.

Creating an HTML Test Harness

A test harness is basically just a web page that lets you run your Jasmine tests and review the test results. It is recommended that you include your test cases as external JavaScript files.

The Jasmine engine is initialized on window load and processes the test cases you defined using the ‘describe’ statement. After all test cases are run, the Jasmine HtmlReporter creates a styled test report and appends it to the body tag.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
  <title>My Test Report</title>
  <link rel="stylesheet" type="text/css" href="jasmine/lib/jasmine-x.x.x/jasmine.css">
  <script type="text/javascript" src="jasmine/lib/jasmine-x.x.x/jasmine.js"></script>
  <script type="text/javascript" src="jasmine/lib/jasmine-x.x.x/jasmine-html.js"></script>
  <script type="text/javascript" src="jasmine/lib/jasmine-x.x.x/boot.js"></script>

  <script type="text/javascript" src="path/test-cases-1.js"></script>
  <script type="text/javascript" src="path/test-cases-2.js"></script>
  <script type="text/javascript" src="path/test-cases-3.js"></script>
</head>
<body>
</body>
</html>

And that’s it. Hopefully this blog article can get you started in the right direction and make unit testing a chore that’s a bit easier to bear.

Author Description

justmobiledev

No comments yet.

Join the Conversation