Mocking jQuery Ajax Calls with Random Templated Data

In a recent blog post, Mocking the jQuery Ajax Call in ASP.NET MVC 3 Music Store , I showed you how you could use the $.mockjax library, written by Jonathan Sharp, to intercept AJAX requests and return a mocked response. This tool can be especially useful when trying to code your front-end, while the back-end piece is either isn’t available or accessible.

Another useful library that you may consider when building quick prototypes is $.mockJSON, written by Menno van Slooten. This library has some of the same features as $.mockjax, but the piece I’d like to focus on is the random data tempting feature. This can be very handy when you want to mock a JSON response from a AJAX call, but instead of manually building the response you can build a template to do it for you.

To demonstrate using this random data technique, I decided to use the SlickGrid jQuery Plugin and populate it with the JSON response from an AJAX call. Since the AJAX call doesn’t exist, I am going to use $.mockjax to return the response using random data generated from $.mockJSON.

The following code is what is necessary to populate the SlickGrid with data from an AJAX call.

<pre>(function($) {

var grid,
columns = [
{id:”firstName”, name:”First Name”, field:”firstName”, width:70},
{id:”lastName”, name:”Last Name”, field:”lastName”, width:70},
{id:”email”, name:”Email”, field:”email”, width:170},
{id:”percentHealth”, name:”% Health”, field:”percentHealth”, width:90, formatter:GraphicalPercentCompleteCellFormatter},
{id:”birthday”, name:”Birthday”, field:”birthday”, width:70},
{id:”married”, name:”Married”, field:”married”, width:50, formatter:BoolCellFormatter}
],
options = {
editable: false,
enableAddRow: false,
enableCellNavigation: true,
rowCssClasses: function(item) {
return (item.percentHealth >= 80) ?
“healthy” : “”;
}
};

$.ajax({
url: “/Contact/List”,
type: “GET”,
dataType: “json”,
success: function(data, textStatus, xhr) {
grid = new Slick.Grid(“#myGrid”,
data.contacts, columns, options);
},
error: function(xhr, textStatus, errorThrown) {
console.log(“Error: “ + textStatus);
}
});

function BoolCellFormatter(row, cell, value,
columnDef, dataContext) {
return value ? “✔” : “”;
};

}(jQuery));
</pre>At this point, I don’t have the '/Contact/List' endpoint defined so if I executed the above code I would get a GET http://fiddle.jshell.net/Contact/List 404 (NOT FOUND) error in my console. If I did want to test the behavior of my front-end without depending on a back-end existing, then I can add an additional $.mockjax statement to intercept the call and respond with some random data provided by $.mockjson.

<pre>$.mockjax({
url: ‘/Contact/List’,
responseTime: 750,
responseText: $.mockJSON.generateFromTemplate({
“contacts
50-500”: [{
“married
0-1”: true,
“email” : “@EMAIL”,
“firstName”: “@MALE_FIRST_NAME”,
“lastName”: “@LAST_NAME”,
“birthday”: “@DATE_MM/@DATE_DD/@DATE_YYYY”,
“percentHealth
0-100”: 0
}]
})
});
</pre>The above code will intercept any AJAX requests with the '/Contact/List' endpoint and will use the template passed to $.mockJSON as the response. The template will generate between 50 and 500 contacts each having male first names and having a health ranging from 0 to 100. Each contact will have a random email, birthday, and married boolean field. You can find out more information as to what $.mockJSON supports and how you can extend it from their website.

The following JSON snippet is an example of what the above $.mockJSON template will generate. The above template would generate between 50 to 500 contacts, but for brevity I just included 4.

<pre>{
“contacts”: [{
“married”: false,
“email”: “u.lewis@gonzalez.com”,
“firstName”: “Paul”,
“lastName”: “Martinez”,
“birthday”: “12/16/2005”,
“percentHealth”: 37},
{
“married”: false,
“email”: “k.hernandez@smith.com”,
“firstName”: “Daniel”,
“lastName”: “Gonzalez”,
“birthday”: “07/11/1997”,
“percentHealth”: 1},
{
“married”: true,
“email”: “c.thomas@taylor.com”,
“firstName”: “David”,
“lastName”: “Lewis”,
“birthday”: “04/13/2007”,
“percentHealth”: 62},
{
“married”: true,
“email”: “v.davis@lee.com”,
“firstName”: “Richard”,
“lastName”: “Rodriguez”,
“birthday”: “05/10/2007”,
“percentHealth”: 6}]

//A bunch more…

}
</pre>Now, since we have some data coming back from our AJAX request, we can run our code again and proceed to get our front-end working as intended.



View Demo Edit Demo

If you enjoyed this post, please consider sharing it with others via the following Twitter or Reddit buttons. Also, feel free to checkout my egghead.io profile page for addition free and subscription lessons, collections, and courses. As always, you can reach out to me on Twitter at @elijahmanor. Thanks and have a blessed day!

Reddit