Why fake AJAX requests at first place?
Sometimes, JavaScript application needs to communicate heavily with network and testing could become more tedious due to network timeouts and other race conditions issues. In such scenario , it’s better to test your app with simulated AJAX request called Mock or Fake AJAX requests. This way, JavaScript code could decouple actual AJAX requests and simply test your app.
jQuery.mockjax Plugin
This plugin extends $.ajax() function and adds wrapper to it using $.mockjax() function. So, once javascript defines that function and then call jQuery ajax request, it mocks the actual ajax request.
Simple Code:-
$.mockjax({ url: "hello.php", responseTime: 0, responseText: 'A text response from mock ajax' });
So here, after this code $.ajax() code will be executed with URL hello.php but whatever server sends from hello.php response, the output will be overloaded by $.mockjax() function’s responseText.
i.e. A text response from mock
This plugin is available to download – https://github.com/appendto/jquery-mockjax
jQuery.mockjax demo examples
-
Simple Fake (Mock) request to server via mockjax
HTML Code:
<p align="center"><button onclick="sayHelloFake();" >Test Fack Ajax Request</button></p> <div id="output_fake" class="output"></div>
jQuery code:
$.mockjax({ url: "hello.php", responseTime: 0, responseText: 'A text response from mock' }); $.ajax({ url: "hello.php" }).done(function(response) { $('#output_fake').html(response); $.mockjaxClear(); });
-
JSON mock request implementation via mockjax
HTML Code:
<p align="center"> <button onclick="sayHelloFakeJSON();" > Test Fack Ajax Request </button> </p> <div id="output_fake_json" class="output"> </div>
JavaScript Code:
Here proxy settings is set to sample.json so instead of making request to hello.php mockjax will fetch sample.json and throw its content as ajax output.
$.mockjax({ url: "hello.php", proxy: 'sample.json', responseTime: 0, dataType: 'json' }); $.ajax({ url: "hello.php", dataType: 'json' }).done(function(json_response) { var names = []; for (i in json_response.employees) { names.push(json_response.employees[i].firstName); } output = names.join("<br/>"); $('#output_fake_json').html(output); $.mockjaxClear(); });
sample.json file contents
{ "employees": [{ "firstName": "Vikas", "lastName": "Bhagwagar" }, { "firstName": "Gaurav", "lastName": "Patel" }, { "firstName": "Ankur", "lastName": "Shah" }] }
Output:
What’s Next?
Check all demos in action here – http://code.vikaskbh.com/mockjax/