Monday, March 23, 2009

QUnit for javascript unit testing - my recommendations

QUnit - the unit testing test runner used for jQuery has turned out to be a valuable investment and javascript related bugs have been reduced considerably in a project I have been working on primarily due to its adoption.

I am not going to explain how to integrate QUnit tests, to learn how to do so please refer to http://docs.jquery.com/QUnit

The following are points of note in relation to how I have applied QUnit:

1. Have a 1-1 relationship between your js file and the QUnit htm file i.e. example.js should have a corresponding example.htm file

2. As all tests for a particular js file are in a single test QUnit .htm file, I tend to only use a single module. Using the module, you can perform setup and teardown functionality (which gets executed for every QUnit test)


module("sample module",
{
setup: function()
{
//do setup stuff...
}
teardown: function()
{
//do teardown stuff...
}
});

test("first test with setup")
{
// set conditions
$("#control1").val("testval");

// execute javascript function
sampleFunction();

// assert
assertTrue($("#control2").val(), 10);
};


3. All HTML controls that are used by the javascript you are testing need to be replicated in the .htm file.

4. All tests are similar to above in format i.e. set, execute and assert

The only problem I currently have is integrating QUnit tests into automated builds - using WatiN! - Will do future post when this issue is resolved

No comments:

Post a Comment