How to spy jQuery AJAX request?

元气小坏坏 提交于 2019-12-05 09:23:55

Here's a walkthrough:

If you use the code in number 2, you are invoking the ajax function on jquery:

return $.ajax({
  url: backendRouter.generate('feedback_send'),
  type: 'POST',
  dataType: 'json',
  data: {
    message: message
  }
...

after calling this function with those parameters, jQuery returns a jqHR that happens to have a success function defined. That success function is then invoked:

...
}).success(callback);

All is well so far until your jasmine test spies on the ajax function. The same options you used to invoke $.ajax are passed to this new spy.

// this is the value of the options parameter
{
    url: backendRouter.generate('feedback_send'),
    type: 'POST',
    dataType: 'json',
    data: {
        message: message
    }
}

When this object is passed, your fake function actually attempts to call options.success, which does not exist! Hence the error.

Steve t

There is a jquery plugin that uses sinonjs with qunit and provides a much easier way to write ajax tests and get expected results.

Take a look at jqueryspy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!