2014-04-22 58 views
0

該任務的描述。我想測試使用$ .get加載資源列表的代碼。使用jasmine返回測試ajax請求返回TypeError

所以,源代碼:

fetchTemplates: function(list, cb){ 
    var promises = [], 
     $container = $('#templates'); 
    Object.keys(list).forEach(function(tplSelector){ 
     if($(tplSelector).length > 0){ return; } 

     var promise = $.get(list[tplSelector]); 
     promise 
      .done(function(tplHtml){ 

       $container.append(tplHtml); 
      }) 
      .fail(function(){ 
       console.warn('Template "' + tplSelector + " not found by url:" + list[tplSelector]); 
      }); 

     promises.push(promise); 
    }); 

    return $.when.apply($,promises).done(cb); 
} 

測試套件:

it("Correct template fetching", function (done) { 
     var fetchResult = viewManager.fetchTemplates({ 
      '#helpTpl': 'somecorrectaddress' 
     }); 
     fetchResult.done(function() { 
      expect(true).toBeTruthy(); 
      done(); 
     }); 
     fetchResult.fail(function() { 
      expect(false).toBeTruthy(); 
      done(); 
     }); 
}); 

它所產生。測試通過,但會產生一個錯誤: 類型錯誤:「空」不是一個對象(評價「this.results_.addResult」)在jasmine.js 如通過2348

所以,測試用例標記?。但是整個測試套件仍然會產生上面的錯誤(並且這種方法是唯一的一種異步方法,其他部分很容易測試)。我的想法是,由於測試方法包含異步操作和承諾 - 結果沒有正確處理,因此TypeError。所以我加了jasmine async「done()」來處理這個問題 - 遺憾的是沒有任何改變。另外值得注意的是,如果我使用「iit」在套件中只保留一個測試 - 不會產生錯誤。搜索沒有找到類似的案例。有任何想法嗎?

回答

0

你需要在'runs()'中用'waitsFor()'包裝你的異步調用,閱讀文檔here。我從來沒有與jquery合作過,但在你的函數中嘗試如下內容:

var done = false; 
var that = this; 

runs(function() { 
    //your async test goes here 
    that.done = true; 
}); 

waitsFor(function() { 
    return that.done; 
}, "async code failed", 2000);