weixin_33725239 2012-03-29 18:33 采纳率: 0%
浏览 22

jQuery Ajax测试不起作用

I am trying to test a very simple jQuery plugin which simply calls $.ajax method and put its content into a element. For testing I am using JsTestDriver and Sinon for mocking.

Plugin file looks:

(function($) {
    $.fn.transfer = function() {

    $.ajax({
        url : 'friends',
    type : 'GET',
    contentType : 'application/json',
    dataType : 'json',
    success : function(html) {
        console.log("-"+html+"-");
        console.log($(this));
        $(this).html(html);
        console.log("+"+$(this).html()+"+")
    }
});
};
})(jQuery);

In theory very simple plugin.

And then I have written a unit test mocking success function:

TestCase("Ajax ", {
    'test response' : function () {
        /*:DOC divElement = <div id="container" style="height: 100px;"></div>*/
        sinon.stub(jQuery, "ajax").yieldsTo(
            "success", 'alex');
        $(this.divElement).transfer();
        console.log("*"+$(this.divElement).text()+"*");
    }
});

it seems correct too. Then if you execute this test, next lines are printed through console:

[LOG] -alex-

[LOG] [object Object]

[LOG] +null+

[LOG] **

So success function receives correctly "alex" string. Then $(this) reference is printed, message is set with html() function and when I log previous set value, a null is returned. And last log message is in test file, where as you can see ajax text is not set.

Does anybody know what I am doing wrong? Because I am sure I am missing something that now I cannot see.

  • 写回答

2条回答 默认 最新

  • weixin_33709609 2012-05-10 23:39
    关注

    Use Synchronous AJAX

    JS Test driver and most testing frameworks I know of have a bit of a problem handling asynchronous javascript, basically the disjointed nature of asynchronous calls screws up the order of test execution (think: test 2 starts executing before test 1 is finished). For this reason try using synchornous ajax calls for the duration of your tests by setting the global async property with jQuery.ajaxSetup().

    // Use synchronous AJAX
    jQuery.ajaxSetup({async: false});
    
    TestCase("Ajax ", {
        'test1' : function () {
            // etc...
        }
    });
    
    // Revert to default
    jQuery.ajaxSetup({async: true});
    
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题