Thursday, November 7, 2013

AngularJS: Karma and Jasmine

This is a primer on javascript unit testing, however there's no AngularJS in this post. But since I got to know Karma and Jasmine by way of AngularJS and I intend to use Karma and Jasmine for AngularJS, I decided to include AngularJS in the title ツ


Installation steps:

* Install nodejs: http://nodejs.org/dist/v0.10.21/node-v0.10.21.pkg
* Go to Terminal, logon as administrator, type: sudo bash
* Type: npm install -g karma


I followed the instruction here: http://www.tuesdaydeveloper.com/2013/06/angularjs-testing-with-karma-and-jasmine/, but since I just wanted to check a working example of karma + jasmine first, I decided to make the testing really very basic. After the karma successfully installed, exit out of administrator, create a sampletest directory placed in your home directory, while at commandline:

$ mkdir ~/sampletest
$ cd ~/sampletest






In the same directory, create a file named test.js, this file will be monitored as we specified *.js during karma config initialization.

function helloWorld(){
    return "This will fail the test"; 
}

describe("Hello world",function(){ 
    it("says hello", function() {
        var s = helloWorld();
        expect(s).toEqual("Hello world!"); 
    });
});

Then start karma:
$ karma start

If you specified a different filename during karma config settings initialization (e.g., karma init karmahin.ka.sana.config.js), put the name of the config file in karma start, e.g., karma start karmahin.ka.sana.config.js

As soon as karma is started, you shall see there's a failing test:




Change the helloWorld() function's return value to "Hello world!"
As soon as you save your file test.js on TextEdit(any editor), you shall see a passed test:



The test is an actual testing of javascript within the browser, try to change the return value of helloWorld() function to a prompt dialog:

function helloWorld() {
    return window.prompt("What's your greet?", "Hi world!");
}

As soon as you hit save, you'll see the browser will refresh and prompts you for an input:


Just press enter, then you'll see a failing test:


This is a great productivity booster on your development workflow. You can see breaking changes as soon as you save your file. There's no need to compile your app in order to unit test it; as soon as you save your file, it is tested on-the-fly! Bye bye compiler tax!



Happy Computing! ツ

No comments:

Post a Comment