Adventures in Mockjax

If you are developing web applications that utilize Ajax (and most do today) and are using jQuery and/or Backbone.js, you should be building with mock Ajax JSON responses.

You can view the code on Github: https://github.com/ibjhb/mockjaxExample  or the examples: http://ibjhb.github.com/mockjaxExample/

Reasons to Mock Ajax

Servers are slow / Rapid Iteration

When developing against a local server, the ajax response will typically 100-300 milliseconds, but could even be longer. If you are developing against a remote end-point, you could see varying response times that could even be 500 milliseconds to over a second. If you are trying to quickly develop an application that takes one second per response, it is going to take a while and you are going to get frustrated and/or bored. The faster the response time, the faster you can develop.

Endpoints Unavailable or Developing on an Airplane

There are a number of reasons that an API endpoint could be unavailable and inevitably, it will be when you want to work on your application. This can be very frustrating and could even cause you to miss a deadline. Additionally, if you are at a location or on an airplane that doesn’t supply WiFi, mocking Ajax responses would allow you to continue working.

Undeveloped Endpoints

If you are working in a team, or even on your own project, and the server-side code isn’t completed yet, Ajax mocking would allow you to complete the front-end code before the back-end is complete. Additionally, it allows you and whoever is developing the API to agree upon JSON response structures to ensure they don’t change unexpectedly during development.

Unit Testing

After rapid iteration, unit testing is probably the number one reason for mocking. The same mocks you use to develop your application become the ‘stone copies’ of your responses and objects in your unit tests. If you try to unit test against a live server, or even a unit test server, it is very possible that the data you expect isn’t the data that is returned. This could cause your unit test assertions to fail, even though the code is technically working properly. Mocking prevents this problem.

Slow or Unavailable Server Simulation

How does your application handle a slow or unavailable remote server? Without mocking, this would be difficult to handle consistently, especially if you don’t control the end-point. When mocking, you can control the response delay and intentionally simulate a slow or unavailable server reliably.

Introducing Mockjax

AppendTo’s Mockjax is a simple but powerful interface for simulating ajax responses. Below, we will explore different uses cases of the library.

Simple Example

In this example, we’re going to setup the most basic mock. If you run the code in example one, you’ll notice it outputs ‘Your beer today is Sam Adams’. If you open Firebug or the console. you’ll notice that Mockjax has logged: ‘MOCK GET: /api/beer/random’. This lets us know we’re mocking, so we don’t forget if we’re debugging in the future.

$.mockjax({
  url: '/api/beer/random',
  responseTime: 150,
  responseText: {
   success        : true
   ,beerName       : 'Sam Adams'
 }
});

$.getJSON('/api/beer/random', function(resp){
 var html = (resp.success) ? 'Your random beer is ' + resp.beerName : 'No beer today';
 $('#content').html(html);
});

URL Matching

Mockjax allows for three ways to define the URL:

  • Direct matching (seen above in the Simple Example)
  • Wildcards (notice the “*” in the URL)
    $.mockjax({
      url: '/api/beer/*',
    });
    
  • Regular Expressions (this would match ‘/api/beer’ and ‘/api/wine’ but not ‘/api/cheese’)
    $.mockjax({
     url: /^\/api\/(beer|wine)$/i
    });
    

Advanced Callback Responses

Mockjax also allows you to specify a callback response instead of a specific responseText. This allows us to define the response programmatically. To view the functional example, view the Callback Response Example.

$.mockjax(function(settings){
 // Try to match our API URL string
  var service = settings.url.match(/\/api\/beer\/get\/(.*)$/i);

 // If we find a match, handle the response
  if (service) {

    // Convert the string to a number
   var beer_id = Number(service[1]);

   // JavaScript counts from 0
   var response = ibjhb.mock.beer[beer_id - 1];

    // If the response doesn't exist, defer to making an ajax,
   // otherwise create our return JSON packet to be returned
   return (typeof response === 'undefined')
      ? undefined
     :   {
         responseText : {
             success  : true
            ,beer   : response
          }
       }
 }
 return;
});

If you read through the JavaScript comments, you’ll get an idea of this more complex example.

Latency Simulations

With Mockjax, we can also simulate slow servers. You can add a ‘responseTime’ property to the function call:

$.mockjax({
  url: '/api/beer/random'
 ,responseTime: 5000  // 5 seconds
 ,responseText: 'Text from a slow server'
});

This example would wait five seconds before returning a response. Be sure to specify the value in milliseconds.

HTTP Response Status Simulations

We can also simulate an error from the server:

$.mockjax({
       url: '/api/beer/random',
       responseTime: 750
       ,status: 500   // Simulate 500 error
       ,responseText: 'Text from a slow server'
});

We can also simulate a server timeout:

$.mockjax({
 url: '/api/beer/random',
  isTimeout: true
});

Conclusion

As you can see, Mockjax is a powerful library that can speed up your development. Be sure to check out the full feature set on Github.