Get your team started on a custom learning journey today!
Our Boulder, CO-based learning experts are ready to help!
Get your team started on a custom learning journey today!
Our Boulder, CO-based learning experts are ready to help!
Follow us on LinkedIn for our latest data and tips!
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)
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.
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:
{ "status": "success", "fortune" : "Are you a turtle?" }
To pull the fortune into our page, we’d use the following HTML & jQuery code:
<!DOCTYPE html> <html> <head> <title>Fortune App</title> <script src="https://code.jquery.com/jquery-1.4.2.min.js"></script> </head> <body> <div id="fortune"></div> </body> </html>
$.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' ); } });
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:
$.mockjax({ url: '/restful/fortune', responseTime: 750, responseText: { status: 'success', fortune: 'Are you a turtle?' } });
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.
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.
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.
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:
$.mockjax({ url: '/url/to/rest-service' });
or contain a *
as a wildcard:
$.mockjax({ // Matches /data/quote, /data/tweet etc. url: '/data/*' });
or a full regular expression:
$.mockjax({ // Matches /data/quote, /data/tweet but not /data/quotes url: /^/data/(quote|tweet)$/i });
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.
A simple text response would be:
$.mockjax({ url: '/restful/api', responseText: 'A text response from the server' });
A simple XML response would be:
$.mockjax({ url: '/restful/api', // Need to include the xmlDOM plugin to have this translated into a DOM responseXML: '<document><quote>Hello world!</quote></document>' });
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
.
$.mockjax({ url: '/restful/api', proxy: '/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.
$.mockjax({ url: '/restful/api', response: function() { this.responseText = 'Hello world!'; } });
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 network and server latency for a mock is as simple as adding a responseTime
property to your mock definition:
$.mockjax({ url: '/restful/api', // Simulate a network latency of 750ms responseTime: 750, responseText: 'A text response from the server' });
It’s also possible to simulate response statuses other than 200 (default for Mockjax) by simply adding a status
property.
$.mockjax({ url: '/restful/api', // Server 500 error occurred status: 500, responseTime: 750, responseText: 'A text response from the server' });
You can set the content type to associate with the mock response, in the example below, we’re setting a json content type.
$.mockjax({ url: '/restful/api', contentType: 'text/json', responseText: { hello: 'World!' } });
Additional HTTP Response Headers may be provided by setting a key in the headers object literal:
$.mockjax({ url: '/restful/api', contentType: 'text/json', responseText: { hello: 'World!' }, headers: { etag: 'xyz123' } });
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:
$.mockjax({ url: '/restful/api', isTimeout: true });
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:
$.mockjax(function(settings) { // settings.url == '/restful/<service>' var service = settings.url.match(//restful/(.*)$/); if ( service ) { return { proxy: '/mocks/' + service[1] + '.json' }; } return; });
It’s also possible to dynamically generate the response text upon each request by implementing a callback function on the response
parameter:
$.mockjax({ url: '/restful/webservice', dataType: 'json', response: function(settings) { this.responseText = { say: 'random ' + Math.random() }; } });
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:
$.mockjaxSettings = { status: 200, responseTime: 500, isTimeout: false, contentType: 'text/plain', response: '', responseText: '', responseXML: '', proxy: '', lastModified: null, etag: '' };
To overwrite a particular settings such as the default content-type, you would do the following:
$.mockjaxSettings.contentType = 'text/json';
Remove all mockjax handlers:
$.mockjaxClear();
var id = $.mockjax({ ... }); $.mockjaxClear(id);
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!
Customized Technical Learning Solutions to Help Attract and Retain Talented Developers
Let DI help you design solutions to onboard, upskill or reskill your software development organization. Fully customized. 100% guaranteed.
DevelopIntelligence leads technical and software development learning programs for Fortune 500 companies. We provide learning solutions for hundreds of thousands of engineers for over 250 global brands.
“I appreciated the instructor’s technique of writing live code examples rather than using fixed slide decks to present the material.”
VMwareDevelopIntelligence has been in the technical/software development learning and training industry for nearly 20 years. We’ve provided learning solutions to more than 48,000 engineers, across 220 organizations worldwide.
Thank you for everyone who joined us this past year to hear about our proven methods of attracting and retaining tech talent.
© 2013 - 2022 DevelopIntelligence LLC - Privacy Policy
Let's review your current tech training programs and we'll help you baseline your success against some of our big industry partners. In this 30-minute meeting, we'll share our data/insights on what's working and what's not.
Training Journal sat down with our CEO for his thoughts on what’s working, and what’s not working.