Saturday, April 19, 2014

Unit testing with javascript

UNIT TESTING

Well, I wrote some unit test for my project before six months, After that, I had left it and I had been working on the code without unit testing, I realized it's really hard to maintain the code without unit testing, Lots of time I am consuming for manual testing and maintain the code as it's complexity is increasing , So I want to make my code very maintainable, modularize with automate testing by using unit test.

So in this context I want to write some basic points about unit testing,

Why we used unit testing?
First of all unit testing means you have to test each unit of your code, which means your code would be very modularize, for write unit testing you need to put your code into particular function, and the function/method would be tested, we expect to do particular action by that function.

Whatever problem will be occured in your application, you would know on which function/method it's affecting.
You can make changes code without worry about it's bad effect into code because after changes the code you can run all the test at once and can see it's effect on partcular part of the code. You can fix these issue by working on particular code if there is any.

I am using the qUnit testing framework for unit testing of my application, which is very simple to use, It has various assertion.

Main asserstion

Check for for boolean(true, false) value
ok(true);
This assertion is passed when the condition is true.

Check for value equalness
equal(fval, sval) 
This assertion is passed when fval and sval are true, fails if these are not equal

Check equalness of value and data type.
deepEqual(1, "1");
This assertion does check it's data type also, above test would be failed.

And also it is used to compare the object like,
deepEqual({fname:'suman'}, {fname:'suman'}); 
The above assertion would be passed.

When you need to do test asynchronous function then you can use asyncTest(), For example you have a replay() function which is executed for 2 seconds. You can write the code for testing like this.

asynchTest("testing for replay", function (){
    replay();
    setTimeout(
    function (){
//this lastId is last executed id from replay();
equal(lastid, 20, the last id should be 20);
}, 
2100
    );
});

Here we invoked the replay() function, after execute this function with 2 seconds, the value of lastId should be 20, so we would check this value by running test after 2.1(2100) seconds.

As I will grip more about this will update the article.

No comments:

Post a Comment