如何监视jQuery AJAX请求?

以下两种实现ajaxRequest(1)(2)的方法应该是等效的。
话说回来:

  1. 为什么unit testing(3)validation回调是否已执行,成功进入(1)并失败进入(2)?
  2. 我应该如何重写测试(3)来监视(2)中的成功回调?
  3. 如果我尝试使用sinon和代码(2)来stub jQuery.ajax ,我会收到错误。 我应该怎么解决?

请参阅代码(3)中的注释以获取更多详细信息。


(1)

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

(2)

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

(3)

 it("should execute the callback function on success", function () { spyOn($, "ajax").andCallFake(function(options) { options.success(); }); // If I use the code (2) I get the following error // TypeError: Object # has no method 'success' var callback = jasmine.createSpy(); ajaxRequest('some message', callback); expect(callback).toHaveBeenCalled(); }); 

(4)

 it("makes a GET request for todo items", function () { sinon.stub(jQuery, 'ajax'); backendController.ajaxRequest('some message', sinon.spy()); // Cannot call method 'success' of undefined }); 

这是一个演练:

如果使用数字2中的代码,则在jquery上调用ajax函数:

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

在使用这些参数调用此函数之后,jQuery返回恰好定义了成功函数的jqHR 。 然后调用该成功函数:

 ... }).success(callback); 

到目前为止一切都很好,直到你的茉莉花测试间谍ajaxfunction。 您用来调用$.ajax的相同选项将传递给这个新的间谍。

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

传递此对象时,您的假函数实际上会尝试调用不存在的options.success ! 因此错误。

有一个jquery插件,它使用带有qunit并提供了一种更简单的方法来编写ajax测试并获得预期的结果。

看看jqueryspy