如何假JQuery.ajax()回应? [英] How to fake JQuery.ajax() response?

查看:295
本文介绍了如何假JQuery.ajax()回应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一些QUnit测试一个JavaScript,使AJAX调用。

I am writing some QUnit tests for a javascript that makes ajax calls.

有关隔离我重写 $。阿贾克斯写一个AJAX调用一个变量的参数数组。这个工程测试方法如何使用AJAX功能,但我很难测试 $的成功处理程序。负载()

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()

这是在 http://api.jquery.com/load/ 文档:

当检测到成功的响应(即当textStatus是成功或notmodified),.load()设置匹配元素的HTML内容返回的数据

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.

有没有进一步的阅读,如何JQuery的/的浏览器是否支持AJAX调用返回? 我怎样才能复制一个成功的Ajax调用的行为?

Is there any further reading as to how JQuery/the browser works with ajax call returns? How can I replicate the behaviour of a successful ajax call?

推荐答案

阅读启发@Robusto和@val后,我发现了一个方法,它的工作原理:

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");
};

而不是引发任何真正的$阿贾克斯code中的事件或触发任何事件

,我有我的假Ajax对象调用的函数(被传递作为一个参数 $。阿贾克斯())作为我的假功能部分。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆