Unit testing Javascript event handlers or any other asynchronous delegate calls using jsUnit


I had to nock up a test for a simple method I had added to a connection manager class. The class tracks wether the client browser has a current connection to the server, and the method I added was simple “check connection” which wrapped prototypejs Ajax.Request method; you basically call the method with a filename and a success and failure call back. I wanted to confirm that, given an accessible filename, the checker would call the passed delegate for success and set a few flags internal to the class.

We needed to make sure the Ajax.Request had totally completed and the result was ready to be tested before the jsUnit test was executed, which meant some how imposing a delay which coudl be cleared once one of the callbacks had fired.

The solution was simple; add a setUpPage function to the page which is a reserved function name which the jsUnit framework looks for. If this function exists it will hold off executing the tests until the setUpPageStatus variable is set to ‘complete’.

My final test for the success case looked something like this;

status = '';

function setUpPage() {
	myConnectionStatus = new ConnectionStatus();
	myConnectionStatus.checkConnection(
		"test.txt", 
		function() { // success callback
			status = 'success called'; 
			setUpPageStatus = 'complete'; 
		}, 
		function() { // failure callback
			status = 'failure called'; 
			setUpPageStatus = 'complete'; 
		}
	);
}

function test_CheckConnectionCnxOK() {
	assertEquals('The success handler should have been called', 'success called', status);
	assertTrue('Connection should be set to online', myConnectionStatus.isOnLine());
}
  1. No comments yet.
(will not be published)