Currently I've been working on writing acceptance test cases for my project in which there were lot of scenarios where I'd to use mocking/stubbing for which I used MockJax plugin of jquery.

So I'm sharing some examples which might be useful to someone.

A simple mock request using mockjax plugin can be written as

$.mockjax({
  url: '/posts/1',
  responseTime: 500,
  responseText: {
    status: 'success',
    post: 'Mockjax Plugin for mocking or simulating ajax requests and responses'
  }
});

Here we can specify the time it will take to get the response and the text which we'll be getting in the response. This kind of response is also known as inline response, you can also specify response in XML. For example

$.mockjax({
  url: '/posts/1',
  responseXML: '<document><>First Post!<></document>'
});

If you want to redirect request to some other URL then you can also provide a proxy . For Example

$.mockjax({
  url: '/posts/1',
  proxy: '/data/response.json'
});

Here mockjax plugin will intercept response for 'posts/1' url and redirect it to data/response.json

You can also provide status code along with responseText. For example,

$.mockjax({
  url: '/posts/1',
  // Not found
  status: 404,
  responseText: 'Post not found'
});

We can also pass the headers by setting a key value pair in headers object. For example

$.mockjax({
  url: '/posts/1',
  responseText: {
    post: 'mockjax headers'
  },
  headers: {
    abc: '123'
  }
});

Source: https://github.com/jakerella/jquery-mockjax

Your comment

*

*