Testing JQuery AJAX communication code
I developed a JQuery Application using TDD these last couple of days. During the testing I used a new technique for testing my AJAX calls, so I thought I’d blog about how I test AJAX calls done by JQuery.
First of you have to see that there are several things to test in just a simple $.ajax call. There is not only all the combinations of the options, there is the behaviour of what to do when the call fails, or is successfull, or times out. There is a boundary between the JavaScript code and the server, will you pass it? Will you test the communication with a server, or even a mocked server using an XML file?
I’ve been testing $.ajax get operations using XML files as a mocked server backend for a while, but recently I mocked it instead.
Mocking $.Ajax requests is quite easy. Before you execute the code that will make the AJAX call, you exchange the ajax function.
$.ajax() = function(options) { options.fail(); };
The above line of codes forces the following ajax calls to automatically execute their fail callbacks. The function can easily be changed to simulate different behaviour of the AJAX requests.
Using this technique there is a risk, that the tests your writing become whitebox testing. The ajax mocking code becomes twins of the code your testing, resulting in a verification that the code is written as is, but not testing that it does what it should do.