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
|