Mock Your Ajax Requests with Mockjax for Rapid Development

By |July 22nd, 2010|Categories: AJAX, Patterns, Plugins|

Most backend developers are familiar with the concepts of mocking objects or stubbing in methods for unit testing. For those not familiar with mocking, it’s the simulation of an interface or API for testing or integration development purposes. Mocking with front-end development though is still quite new.

Much of the development that appendTo does focuses on front-end development tied to RESTFUL web services. As such we’re able to spec out the service contract and data format at the beginning of a project and develop the front-end interface against mock data while the back end team builds the production services.

I originally developed this plugin for appendTo back in March of this year and our team has been using it in all of our projects since. appendTo is committed to sharing our tools and best practices with the community so it’s with much excitement that we’re releasing this plugin. (A sneak peek was available to the Silicon Valley JavaScript Users Group and those that attended our OSCON tutorial)
[cta id=”3166″ align=”none”]

Plugin Overview

Abstract: The mockjax plugin is a development and testing tool for intercepting and simulating ajax requests made with jQuery with a minimal impact on changes to production code.

Overview: Your First Mock

Our first example will be for a simple REST service for a fortune app with the REST endpoint being /restful/fortune which returns the following JSON message:

To pull the fortune into our page, we’d use the following HTML & jQuery code:

At this point if we were to run this code it would fail since the REST service has yet to be implemented. This is where the benefit of the Mockjax Plugin starts to pay off. The first step in using Mockjax is to include the Plugin (you can grab the latest source from github) Once you have that included, you can start intercepting Ajax requests and mocking the responses. So let’s mock out the service by including the following code:

Defining a JOSN string inline requires a JSON.stringify method to be available. For some browsers you may need to include json2.js

What the plugin does at this point is replace the $.ajax method with a wrapper that transparently checks the URL being requested. If the URL matches one defined by $.mockjax(), the plugin intercepts the request and sets up a mock XMLHttpRequest object before executing the jQuery.ajax handler. Otherwise, the request is handed back to the native $.ajax method for normal execution. One benefit in this implementation detail is by simulating the XMLHttpRequest object, the plugin continues to make use of jQuery’s native ajax handling.

As you write code to mock responses, there’s great value in there are no modifications required to production code. The mocks can be transparently inserted. This provides easy integration into most frameworks by including the plugin and mock definitions through your build framework. It’s also possible to include it at run time by listening for a flag query string flag and injecting the plugin and definitions.

Mockjax in Depth

Now let’s look at the various approaches to defining mocks as offered by the plugin. The sections below feature an extensive overview of the flexibility in Mockjax and creating responses.

Data Types Available for Mocking

jQuery is able to handle and parse Text, HTML, JSON, JSONP, Script and XML data formats and Mockjax is able to mock any of those formats. Two things to note, depending upon how you Mock out JSON and JSONP you may need to include json2.js for the JSON.stringify() method. Additionally if you mock XML inline, you’ll need to include the xmlDOM plugin that transforms a string of XML into a DOM object. If you use the proxy approach outlined below, there’s no need to include either the JSON or XMLDOM plugins.

Step 1. Define the URL

The first thing you need to do when mocking a request is define the URL end-point to intercept and mock. As with our example above this can be a simple string:

or contain a * as a wildcard:

or a full regular expression:

Step 2. Define the Response

The second step is to define the type of response. The two main properties you’ll be dealing with are either responseText or responseXML. These properties mirror the native XMLHttpRequest object properties that are set during a live response. There are three different patterns for specifying the responses: Inline, Proxy, and Callback.

Inline Responses

A simple text response would be:

A simple XML response would be:

As you can quickly see, if you have a significant amount of data being mocked this becomes unwieldy. So that brings us to the next pattern of proxying.


In this example below, the Mockjax plugin will intercept requests for /restful/api and redirect them to /mocks/data.json.


In the final response pattern, we can define a callback on the response property and have it set responseText or responseXML as needed.

Advanced Mocking Techniques

At this point we’ve looked at a series of basic mocking techniques with Mockjax and will now unpack some of the additional functionality contained in the plugin.

Simulating Response Time and Latency

Simulating network and server latency for a mock is as simple as adding a responseTime property to your mock definition:

Simulating HTTP Response Statuses

It’s also possible to simulate response statuses other than 200 (default for Mockjax) by simply adding a status property.

Setting the Content-Type

You can set the content type to associate with the mock response, in the example below, we’re setting a json content type.

Setting Additional HTTP Response Headers

Additional HTTP Response Headers may be provided by setting a key in the headers object literal:

Force Simulation of Server Timeouts

Because of the way Mockjax was implemented, it takes advantage of jQuery’s internal timeout handling for requests. But if you’d like to force a timeout for a request you can do so by setting the isTimeout property to true:

Dynamically Generating Mock Definitions

In some situations, all of your REST calls are based upon a URL schema. Mockjax has the ability for you to specify a callback function that is handed the $.ajax request settings. The callback function may then either return false to allow the request to be handled natively, or return an object literal with relevant Mockjax parameters set. Below is an example that rewrites all Ajax requests to proxy to static mocks:

Dynamically Generating Mock Responses

It’s also possible to dynamically generate the response text upon each request by implementing a callback function on the response parameter:

Globally Defining Mockjax Settings

It’s also possible to define the global defaults for all Mockjax requests by overwriting the $.mockjaxSettings object. By default the settings are as follows:

To overwrite a particular settings such as the default content-type, you would do the following:

Removing Mockjax Handlers

Remove all mockjax handlers:

Remove Single Mockjax Handler


So there you have it, Mockjax unpacked! There are a number of additional posts in the pipeline surrounding this topic and how to apply and integrate it with your project. So stay tuned! In the meantime, the plugin code is readily available on github and feel free to report any issues you find in the plugin’s github issue tracker. Enjoy!

Kyle Pennell
Kyle Pennell is the editor of