Testing JavaScript: Mocking jQuery Ajax Calls

When "seriously" developing JavaScript applications we obviously need to write tests. Being a fully dynamic language (similar as Ruby), tests are more necessary than ever since there is no compiler that checks for you all the silly mistakes before you run your code the first time. What also remains important is the distinction between integration tests and unit tests.



So mocking comes to play immediately as I wouldn't want to establish any contact to the server from within my unit tests. Consider the following jQuery call:
function fetchPerson(id){
$.ajax({
type: "GET",
url: "/person/" + id,
success: function(data){
...
}
...
});
}
To steer the "data" that is returned by such ajax call (without actually performing it), you can just override jQuery's ajax method.
(function($){

$.ajax = function(params){
if(params.url === "/person/1"){
params.success({ ... }); //return the data you need
}
};

})(jQuery);
This is the power a dynamic languages gives you and may be very helpful not only while testing but also during development. Consider when you don't yet have the server-side implemented and ready to feed data to your JavaScript rich client? You can program your whole application using jQuery as you'd do and then include an additional file that overrides the jQuery ajax method returning the fake data you'd expect from the server-api. Once the server-side is ready you just remove the JavaScript include containing the jQuery override and you'd start communicate with the real server, without touching any application-code.

Actually it somehow feels a bit like AOP, where you define an aspect telling it to crosscut all ajax calls and replace it with the defined behavior.
Kindle

Comments

0

Your ad here?