Sunday, January 10, 2010

Javascript Testing

Testing javascript codes needs proper design otherwise it can be a headache. Here i want to suggest a testing technique, which may be immature and can be improved.
Write assertion function like this :


function assert(expression, comment)
{
if(!expression)
{
var currentTime = new Date();
var caller = arguments.callee.caller.name;
var error_message = currentTime.getTime()+"\nASSERTION FAILED: '"+comment+
"' \nCALLER: '"+caller+"'";
showError(error_message);
log(error_message);
return 0;
}
return 1;
}


Then use it like this to check if the current condition is acceptable or not( you can check precondition at the beginning of each method and postconditions at the end):



function sortArray(input_array)
{
if(!assert(input_array, "input_array is undefined")) return 0;

//do the sort stuff
var sorted_array = ...
}


This way you can have much cleaner code instead of cheking each parameter one by one with "if" statement. You need to define two method "showError" and "log". Simple definition of "showError" can be an alert. and for "log" function you can report the erro via ajax call to server or just log it in Firebug console. After this you should never see blocks like this in your Javascript code:

if(...)
{
alert("error"); // or any thing else
return 0;
}

No comments:

Post a Comment