By   February 16, 2015

In this post, we will be trying to understand how we can unit test javascript code using Karma and Jasmine.

Karma

Let’s first install Karma. It is available as a node package, so we can use npm to install it.

mehrofiq

Here we are using Karma for running our unit tests. Karma launches a web server that executes the test code against connected web browsers. The tests can run manually or it can also watch files, matching certain grep pattern. After running tests, it can show the results in the command line console. You can read more about karma here.

karma_web

Jasmine

We will be writing our tests using Jasmine for writing unit tests. It provides an easy to use framework for introducing javascript tests.

install-karma-jasmine

Further info about Jasmine’s unit testing features can be found here:
jasmine_further_info

We also need to add support to run it in a browser. Here we are installing chrome launcher for karma.

karma-chrome-launcher

After installing the above packages, you should have a folder created node_modules containing the following packages.

installed-packages

npm – Node Package Manager

Here we are using npm to install these node packages. If you don’t have it installed already, you can get it directly from npmjs.com.

npm-install

Configuring Karma

Now we need to configure karma to run the unit tests. This can be used to automatically set karma to watch files matching certain grep pattern. Here we want to watch all javascript files in the current folder. We will be using jasmine and would be using chrome to run our tests.

configuring_karma

After the above configuration, you should have the following file created in your folder.

karma_conf_js

Writing Unit Tests

Let’s see below how easy is to write our first unit tests. We need to group the tests in describe blocks. Each test is blocked in it blocks. The assertions are added using various expect features provided by the framework.

Running Tests

Before running the tests, we first need to launch karma. If you have followed the above steps, it should also launch chrome and connect it to the karma.

karma_start

Now the server is continuously watching the folder. It would run the test if a new javascript file is added to the folder or an existing file is updated.

test_run

Zindabad!