Monday, May 5, 2014

Things TODO

Below are somethings I want to achieve in 1 year from now.

  1. I am having a feeling that I have lost in touch with the cool frameworks that are being used widely now(AngularJS, Backbone.js, Ractive.js and blah blah blah). I am making it mandatory for me to get to know these frameworks, blog about them, compare them and finally ditch them and go back to writing vanilla js :)
  2. Create a library that one will possibly need while creating web applications
  3. Complete the travel application that I started - justroam.herokuapp.com
  4. Travel to Antartica. After all here the Penguins will jump on your back!
  5. Learn to swim (what if I get drowned in Antartica!!)
  6. Touch my guitar once in a while
  7. Exercise regularly
  8. Think constantly about startup ideas
  9. Complete 50% of my home loan
  10. Finish reading Ponniyin Selvan

Tuesday, September 20, 2011

Unit Testing using QUnit

It has taken a while but this is the continuation of my previous blog on implementing a Test Framework for JavaScript

In this blog I will discuss in detail about writing test case and how it can be executed with ant. But before entering lets be clear that we are writing only unit test cases to test functionality and NOT multibrowser compatibility.

Writing Test Cases using QUnit
QUnit is a simple test suite library from jQuery team. Its a neat library with all the api's you will need for writing a test case. Lets take a simple Calculator class and see how test cases can be written for it


 //calculator.js
 function Calculator() {}
 Calculator.add = function (x, y) {
    return x + y;
 }
 Calculator.subtract = function (x, y) {
    return x - y;
 }
 Calculator.multiply = function(x, y) {
    return (x * y).toFixed(10);
 }
 Calculator.divide = function(x, y) {
    return x/y;
 }



This is how the test file will look for calculator.js


 //testCalculator.js

 module("Calculator")
 test("Addition Test", function() {
    expect(2);
    equals(5 + 5, 10, "postive integer addition");
    equals(5.99 + 3.87, 9.86, "decimal addition");
 });
 test("Multiplication Test", function() {
    expect(1);
    equals(5.99 * 0.1, .599, "decimal multiplication");
 });



Lets get into details.
module -  module is a set of test cases. It is a logical grouping of test case. It is optional but comes in handy when there are test case failures and you want to trace the failure. We will look at this later

test function -  it is inside these test functions we write our test cases. It takes two parameters - name and callback function.

expect -  call this method to say how many assertions you expect to run within the test case. This is useful because at time you would want to write assertions with a loop. You can use this method to keep track of it.

Above 3 are the basic elements to get started with writing test cases.

Download QUnit and check the link for executing this test case. This will produce a html output.
But our intention is to run the test cases in console so as to integrate with ant. So we need to do some extensions.


Extending QUnit
To see the test case execution in console, we will need to extend some of the QUnit methods like log, moduleStart etc...
This is my QUnitExtension.js file


 //QUnitExtension.js
 QUnit.log = function(details) {
print(details.result ? 'PASS ' + details.message
            : 'FAIL ' +  details.message + '\nExpected: ' + details.expected +   '\nActual: ' + details.actual);
 };


 QUnit.moduleStart = function(details) {
print("Module ", details.name, " started...");
 };


 QUnit.moduleDone = function(details) {
print(details.name, " ends", "TOTAL:", details.total, " PASSED:",  details.passed, " FAILED:", details.failed);
 }; 


 //hack for avoiding execution interruption due to errors
 var current_object_parser = QUnit.jsDump.parsers.object;
 QUnit.jsDump.setParser('object', function(obj) {
   if(typeof obj.rhinoException !== 'undefined') {
     return obj.name + " { message: '" + obj.message + "', fileName: '" +  obj.fileName + "', lineNumber: " + obj.lineNumber + " }";
   }
   else {
     return current_object_parser(obj);
   }
 });


Executing the Test Cases
Now we have got test cases and utilities. To execute the test cases in console we need a JavaScript engine and a headless browser. For this we use Rhino as the JavaScript engine and Envjs for headless browser. Rhino+Envjs as a package is available at http://www.envjs.com/releases
Download and build it.

Create a folder test.
Download qunit.js and copy to test folder.
Copy calculator.js, testCalculator.js and QUnitExtension.js to test folder.

We need  a initialization script to load the test files and source files for execution.

//init.js

load('dist/env.rhino.js');
load('test/qunit.js');
load('test/QunitExtension.js');

//config
QUnit.init();
QUnit.config.blocking = true;
QUnit.config.autorun = false;
QUnit.config.updateRate = 0;

load('test/calculator.js');
load('test/testCalculator.js');

QUnit.start();



Once init.js is available we are ready to go.

Run command java -jar rhino/js.jar init.js to see the output.

Integrating with ant
Write a build.xml file with the below target.

    <target name="js-test" description="Runs javascript unit tests">
        <java classname="org.mozilla.javascript.tools.shell.Main" failonerror="true" fork="true">
            <classpath refid="jstest.classpath"/>
            <arg value="-opt"/>
            <arg value="-1"/>
            <arg value="-f"/>
            <arg value="thatcher-env-js-cb738b9/test.js"/>
        </java>
    </target>

To execute use command ant js-test
Its done!

Sunday, June 12, 2011

TDD for Web

Writing unit cases for UI is not a very common development mode and also not very feasible but is possible. We often hear the merits of TDD from a backend developers. No doubt. TDD is good. People have seen the fruits of TDD over time.
Development in UI technology has been at a faster pace in recent times. Power of JavaScript is being appreciated not just for UI but as well for backend.  Most of the web application handle its business logic in both back end and front end for load maintenance. There are also applications that uses UI for just mere representation for data. You don't want to invest time in unit test cases for merely representing UI. Rather I will focus on web applications that handles logic in front end.

Developing a web application
When developing web applications always use object oriented JavaScript. When you do procedural, over time you wont like what you have done.
When developing consider the below points:
  • Understand and list possible use cases
  • Identify and define classes
  • Define Utility classes
  • Define Factory classes
In parallel, define your test cases. Main point - keep your functionality as modular as possible. Even when writing code think about how well you can test it. Don't club two functionality into a single function. Make them separate functions. Function is not just for code reuse. Its for modularity. It will help you unit test your code better.

Unit Testing Web Application
There are lot of test frameworks available in market for JavaScript. QUnit, YUI Test, JS Test Driver etc..
Developing your own test framework will also be an interesting piece of work. Write test cases even before you start writing code. Use cases are very important. If you jump into code your thinking will become narrow and will just focus on the existing requirement. Think wider and write test cases.
Okie. That was easy. You got some requirement wrote test cases and implemented. Now execution. Each test framework has its own way of executing test cases. Example, for QUnit you have to define a HTML page and initialize test classes from there. JS Test Driver has its own browser environment and console. Its all your choice. One major problem will be integrating test cases written in JavaScript with build cycle of your complete product suite. In next blog I will discuss QUnit and how it can be integrated with build.

Saturday, April 23, 2011

Google Chat Bot Reminder

Sometime back I joined CloudSpokes and participated in one of the challenges. The challenge is to create a  reminder service as a google chat bot. User can add this chat bot to their gtalk contacts. When a user enters a reminder say 1h Sign documents, the chat bot after 1 hour will ping back the user with message Sign documents. 
So how useful is this chat bot? People are almost online 24x7 and chat clients are used for both business and personal purposes. With this wide usage of chat services, a reminder service as a chat bot is really cool. It is making life easy as one way or the other we use some sort of reminder service.
To use this reminder service add todotaskbot@appspot.com to your gtalk contact and start using it. Type help to know the advanced features.  With this service you can create and manage reminders. If you are not online at due time of reminder then you will be sent  a mail so that you can act on the reminder later.
For developers, the chat bot is created using Google Application Engine. Source code is available at: http://code.google.com/p/todotaskbot/source/browse/
For feature list you can see: http://code.google.com/p/todotaskbot/source/browse/trunk/README.txt