Unit testing with AJAX

Michelle D'Souza michelle.dsouza at utoronto.ca
Fri Feb 6 19:59:02 UTC 2009


I've spent a couple hours today trying to get the table of contents  
tests passing and now that they are working I thought I'd share what I  
learned (thanks Antranig). The problem I ran into was that the code I  
was testing had an AJAX call in it. I needed to run the test after the  
AJAX call returned. Our general test writing pattern will not work in  
this case, instead I used our event system to run the test. This is  
not a perfect solution since the test knows an implementation detail  
of the code (that there is an AJAX call) but I couldn't think of a  
better way to write this.

If you are going to use this strategy for code you are testing, it is  
important to remember that the test itself needs to start inside the  
event handler. This pattern looks like this:

(function ($) {
     $(document).ready(function () {
             var tests = new jqUnit.TestCase("My Tests");

             var myEventHandler = function () {
                 tests.test("My Test", function () {
                     assertTrue("this is a test", true);
                 });
             };

             var options = {
                 listeners: {
                     myEvent: myEventHandler
                 }
             };

             fluid.myComponent(container, options);
     });
})(jQuery);




------------------------------------------------------
Michelle D'Souza
Software Developer, Fluid Project
Adaptive Technology Resource Centre
University of Toronto