gpt4 book ai didi

javascript - 如何监视 jQuery AJAX 请求?

转载 作者:搜寻专家 更新时间:2023-11-01 04:10:26 24 4
gpt4 key购买 nike

下面两种ajaxRequest的实现方式(1)(2)应该是等价的。
话虽如此:

  1. 为什么验证回调已执行的单元测试 (3) 在 (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 #<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);

到目前为止一切都很好,直到您的 jasmine 测试监视 ajax 函数。您用于调用 $.ajax 的相同选项将传递给这个新 spy 。

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

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

关于javascript - 如何监视 jQuery AJAX 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12088029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com