Testing JavaScript: Mocking jQuery Ajax Calls
2 min read
2 min read
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.
function fetchPerson(id){To steer the "data" that is returned by such ajax call (without actually performing it), you can just override jQuery's
$.ajax({
type: "GET",
url: "/person/" + id,
success: function(data){
...
}
...
});
}
ajax
method.(function($){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.
$.ajax = function(params){
if(params.url === "/person/1"){
params.success({ ... }); //return the data you need
}
};
})(jQuery);