Writing unit test on our Javascript code is beneficial and a good practice.
Here are the 3 main reasons why:
Let’s consider this javascript function:
function displayAddress () {
var address = $('#Address-1'),
parent = address.closest('.form-group.collapse');
if (address.length > 0 && $.trim(address.val()).length > 0 && parent.length > 0) {
parent_wrapper.addClass('in');
}
}
Now, this function is not that testable. Let me break it down.
Rewriting the function to make it testable will result to this:
function displayAddress (address, parent, display_class_name) {
var noAddressFound = (0 === address.length || 0 === $.trim(address.val()).length),
noParentFound = (0 === parent.length);
if (noAddressFound || noParentFound) {
return false;
}
parent.addClass(display_class_name);
return true;
}
Now, we have a testable Javascript function.
Using QUnit as a test suite, we can write our unit test like this.
var display_class_name = 'in';
QUnit.test( "Testing the \"displayAddress\" function with set address", function( assert ) {
var fixture = $( "#qunit-fixture" );
fixture.append('<div class="form-group collapse"><input id="Address-1" type="text" value="1234 Marine Av. Los Angeles, Ca."></div>');
var address = $("#Address-1"),
parent = $(".form-group.collapse");
//we can expect that our function will return true
assert.equal(displayAddress(address,parent,display_class_name), true, "Input address is displayed.");
});
QUnit.test( "Testing the \"displayAddress\" function with no set address", function( assert ) {
var fixture = $( "#qunit-fixture" );
fixture.append('<div class="form-group collapse"><input id="Address-2" type="text" value=""></div>');
var address = $("#Address-2"),
parent = address.parent();
//we can expect that our function will return false
assert.equal(displayAddress(address,parent,display_class_name), false, "Input address is not displayed.");
});