【问题标题】:Not able to spyOn the interleaved success callback of an ajax in Jasmine unit testing无法在 Jasmine 单元测试中监视 ajax 的交错成功回调
【发布时间】:2013-07-10 16:02:13
【问题描述】:

在源代码中,我有一个 getJSON 调用和以下结构中的两个成功回调。

要测试的源代码:

jsonMakeLineOrderData = $.getJSON(url, jsonData,
                                  function (data) {
                                      console.log("Inside 1st callback");   
                                      //… some other statement
                                  }).success(function (data) {      // line# 1
                                            console.log("Inside 2nd callback");
                                            //… some other statement
                                      });

我正在使用 Jasmine 测试框架来测试这个调用的成功块。

为了伪造/模拟 ajax 调用,我使用了 spyOn 实用程序。

我的 Jasmine 测试规范:

it ("Test Function",function(){
    var data = <json_data>;
    var d;
    spyOn($, "ajax").andCallFake(function(params) {
        params.success(data);           // line# 2
        d = $.Deferred();
        d.resolve(data);
        return d.always();
    });
});

在上面的示例中,我能够测试第一个回调,但无法测试第二个回调。

由于测试规范中的第 2 行,第一个回调正在执行。

我尝试使用 jQuery 延迟实例来执行第二个回调,但如果我更改它会抛出 “TypeError: $.getJSON(...).success is not a function” 错误.success() 语句到 .done() 在源文件的第 1 行测试用例工作正常,但我无法使其工作.success(),不幸的是我不打算更改源文件,所以我必须使用 .success()

如果有人有任何解决方案,请告诉我。

提前致谢。

【问题讨论】:

    标签: jquery jasmine


    【解决方案1】:

    你必须返回一个调用回调的函数,如下所示:

    it ("Test Function",function(){
        var data = <json_data>;
        spyOn($, "getJSON").andReturn({success: function(c){c(data)}});
    });
    

    为了更简单的 ajax 测试,我建议 sinonJS 使用 fake server 模拟 ajax 的简单方法。

    【讨论】:

    • 我使用的语法和你建议的一样
    • 感谢安德烈亚斯的回复。我使用了与您提出的实际数据相同的语法,如下所示。 spyOn($, "getJSON").return({success: function(c){c(testData)}});但是得到以下错误 italic TypeError: spyOn(...).return is not a function 我可能做错了,但我不确定我做错了什么。
    • 我的错是andReturn 而不仅仅是return,更新了我的答案。
    • @Andreas,现在我面临一些相关的问题。在我的源代码中,我从其他一些 javascript 函数中调用了 jqXHR.success() 方法,现在我想使用 Jasmine 测试第三个回调的成功块。请在以下评论中找到示例。
    • 要测试的源代码:function TestSourceCode() { jqXHRObject = $.getJSON(url, jsonData,function (data) { // 1st callback //… some other statement }).success(function (data) { // line# 1 // 2nd callback //… some other statement anotherChildFunction(); }); }; function anotherChildFunction (){ //… some other statement jqXHRObject.success(function{ // 3rd callback //… some other statement }); }Jasmine Test Spec codeit ("My Test Case",function(){ var jsonData = ; spyOn($, "ajax"). andReturn({success:function(c){c(jsonData)}}); TestSourceCode (); });`
    猜你喜欢
    • 2012-04-19
    • 1970-01-01
    • 2020-01-26
    • 2018-05-10
    • 2015-10-21
    • 1970-01-01
    • 2023-03-27
    • 2017-06-26
    • 2023-04-01
    相关资源
    最近更新 更多