Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Testing JavaScript: Mocking jQuery Ajax Calls

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.



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.
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus