1024px-Flatirons_Winter_Sunrise_edit_2

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:

[js] { "status": "success",
"fortune" : "Are you a turtle?"
}
[/js]

To pull the fortune into our page, we’d use the following HTML & jQuery code:
[html] <!DOCTYPE html>
<html>
<head>
<title>Fortune App</title>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="fortune"></div>
</body>
</html>
[/html] [js] $.getJSON(‘/restful/fortune’, function(response) {
if ( response.status == ‘success’) {
$(‘#fortune’).html( ‘Your fortune is: ‘ + response.fortune );
} else {
$(‘#fortune’).html( ‘Things do not look good, no fortune was told’ );
}
});
[/js]

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:

[js] $.mockjax({
url: ‘/restful/fortune’,
responseTime: 750,
responseText: {
status: ‘success’,
fortune: ‘Are you a turtle?’
}
});
[/js]

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:

[js] $.mockjax({
url: ‘/url/to/rest-service’
});
[/js]

or contain a * as a wildcard:

[js] $.mockjax({
// Matches /data/quote, /data/tweet etc.
url: ‘/data/*’
});
[/js]

or a full regular expression:

[js] $.mockjax({
// Matches /data/quote, /data/tweet but not /data/quotes
url: /^/data/(quote|tweet)$/i
});
[/js]

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:

[js] $.mockjax({
url: ‘/restful/api’,
responseText: ‘A text response from the server’
});
[/js]

A simple XML response would be:

[js] $.mockjax({
url: ‘/restful/api’,
// Need to include the xmlDOM plugin to have this translated into a DOM
responseXML: ‘<document><quote>Hello world!</quote></document>’
});
[/js]

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.

Proxy

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

[js] $.mockjax({
url: ‘/restful/api’,
proxy: ‘/mocks/data.json’
});
[/js]

Callback

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

[js] $.mockjax({
url: ‘/restful/api’,
response: function() {
this.responseText = ‘Hello world!’;
}
});
[/js]

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:

[js] $.mockjax({
url: ‘/restful/api’,
// Simulate a network latency of 750ms
responseTime: 750,
responseText: ‘A text response from the server’
});
[/js]

Simulating HTTP Response Statuses

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

[js] $.mockjax({
url: ‘/restful/api’,
// Server 500 error occurred
status: 500,
responseTime: 750,
responseText: ‘A text response from the server’
});
[/js]

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.

[js] $.mockjax({
url: ‘/restful/api’,
contentType: ‘text/json’,
responseText: {
hello: ‘World!’
}
});
[/js]

Setting Additional HTTP Response Headers

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

[js] $.mockjax({
url: ‘/restful/api’,
contentType: ‘text/json’,
responseText: {
hello: ‘World!’
},
headers: {
etag: ‘xyz123’
}
});
[/js]

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:

[js] $.mockjax({
url: ‘/restful/api’,
isTimeout: true
});
[/js]

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:

[js] $.mockjax(function(settings) {
// settings.url == ‘/restful/<service>’
var service = settings.url.match(//restful/(.*)$/);
if ( service ) {
return {
proxy: ‘/mocks/’ + service[1] + ‘.json’
};
}
return;
});
[/js]

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:

[js] $.mockjax({
url: ‘/restful/webservice’,
dataType: ‘json’,
response: function(settings) {
this.responseText = { say: ‘random ‘ + Math.random() };
}
});
[/js]

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:

[js] $.mockjaxSettings = {
status: 200,
responseTime: 500,
isTimeout: false,
contentType: ‘text/plain’,
response: ”,
responseText: ”,
responseXML: ”,
proxy: ”,
lastModified: null,
etag: ”
};
[/js]

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

[js] $.mockjaxSettings.contentType = ‘text/json’;
[/js]

Removing Mockjax Handlers

Remove all mockjax handlers:

[js] $.mockjaxClear();
[/js]

Remove Single Mockjax Handler

[js] var id = $.mockjax({

});
$.mockjaxClear(id);
[/js]

Conclusion

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!

Comments