如何伪造 jquery.ajax() 响应? [英] How to fake jquery.ajax() response?
问题描述
我正在为进行 AJAX 调用的 JavaScript 编写一些 QUnit 测试.
为了隔离,我覆盖了 $.ajax
以将 AJAX 调用的参数数组写入变量.这可以测试方法如何使用 AJAX 函数,但我很难测试 $.load()
来自 http://api.jquery.com/load/ 的文档:><块引用>
当检测到成功响应时(即当 textStatus 为success"或notmodified"时),.load() 将匹配元素的 HTML 内容设置为返回的数据.
所以我试图返回一个包含与成功处理程序的变量同名的对象的对象:
//模拟ajax函数$.ajax = 函数(参数){_mockAjaxOptions = 参数;var fakeAjaxSuccess = { responseText: "success", textStatus: "success", XMLHttpRequest: "success" };返回 fakeAjaxSuccess;};
但是这种方法没有奏效.
如何复制成功的 AJAX 调用的行为?
在阅读了@Robusto 和@Val 的启发后,我发现了一个有效的方法:
//模拟ajax函数$.ajax = 函数(参数){_mockAjaxOptions = 参数;//调用成功处理程序param.complete("data", "textStatus", "jqXHR");};
不是从任何真正的 $.ajax 代码中引发事件或通过触发任何事件,我让我的假 ajax 对象调用函数(它作为参数传入 $.ajax()
) 作为我的假函数的一部分.
I am writing some QUnit tests for a JavaScript that makes AJAX calls.
For isolation I overwrite $.ajax
to write the parameter array of an AJAX call to a variable. This works to test how methods use AJAX functions, but I have difficulty testing the success handler of $.load()
From the documentation at http://api.jquery.com/load/:
When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data.
So I have attempted to return an object containing objects with the same name as variables for the success handler:
//Mock ajax function
$.ajax = function (param) {
_mockAjaxOptions = param;
var fakeAjaxSuccess = { responseText: "success", textStatus: "success", XMLHttpRequest: "success" };
return fakeAjaxSuccess;
};
But this approach hasn't worked.
How can I replicate the behaviour of a successful AJAX call?
After reading inspired by @Robusto and @Val, I found a method that works:
//Mock ajax function
$.ajax = function (param) {
_mockAjaxOptions = param;
//call success handler
param.complete("data", "textStatus", "jqXHR");
};
Instead of raising the event from any real $.ajax code or by triggering any events, I have my fake ajax object call the function (which is passed in as a parameter to $.ajax()
) as part of my fake function.
这篇关于如何伪造 jquery.ajax() 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!