:::: MENU ::::

jQuery Fake AJAX requests for ajax testing using mockjax plugin

jquery_logo

Why fake AJAX requests at first place?

Sometimes, JavaScript application needs to communicate heavily with network and testing could became 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:-

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:

    jQuery code:

  • JSON mock request implementation via mockjax

    HTML Code:

    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.

    sample.json file contents

    Output:

What’s Next?

Check all demos in action here – http://code.vikaskbh.com/mockjax/

Share and Enjoy

  • DZone
  • Google Plus
  • LinkedIn
  • Twitter
  • Facebook
  • Email

One Comment

So, what do you think ?

  •