2017-11-25 168 views
0

在我的項目中,我使用jquery和ajax從API獲取提要。這是我使用的代碼:用jasmine測試ajax調用

function loadFeed(id, cb) { 
var feedUrl = allFeeds[id].url, 
    feedName = allFeeds[id].name; 

$.ajax({ 
    type: "POST", 
    url: 'https://rsstojson.com/parseFeed', 
    data: JSON.stringify({url: feedUrl}), 
    contentType:"application/json", 
    success: function (result, status){ 

      var container = $('.feed'), 
       title = $('.header-title'), 
       entries = result.feed.entries, 
       entriesLen = entries.length, 
       entryTemplate = Handlebars.compile($('.tpl-entry').html()); 

      len = entriesLen; 
      title.html(feedName); // Set the header text 
      container.empty();  // Empty out all previous entries 

      /* Loop through the entries we just loaded via the Google 
       * Feed Reader API. We'll then parse that entry against the 
       * entryTemplate (created above using Handlebars) and append 
       * the resulting HTML to the list of entries on the page. 
       */ 
      entries.forEach(function(entry) { 
       container.append(entryTemplate(entry)); 
      }); 

      if (cb) { 
       cb(); 
      } 
      }, 
    error: function (result, status, err){ 
      //run only the callback without attempting to parse result due to error 
      if (cb) { 
       cb(); 
      } 
      }, 
    dataType: "json" 
}); 

}

,現在我想用茉莉花來測試這一點,但不知何故,我不能弄明白。我試圖檢查我的容器(與類「feed」)是否至少有一個條目(類「條目」)附加到它。這是我的代碼中使用茉莉:

describe('Initial Entries', function() { 
    /* TODO: Write a test that ensures when the loadFeed 
    * function is called and completes its work, there is at least 
    * a single .entry element within the .feed container. 
    * Remember, loadFeed() is asynchronous so this test will require 
    * the use of Jasmine's beforeEach and asynchronous done() function. 
    */ 


    beforeEach(function(done) { 
    loadFeed(0); // the async method 
    done(); 
    }); 

    it('should have at least one entry element', function() { 
    expect($(".feed").find(".entry").length).not.toBe(0); 
    }); 

}); 

與整件事的問題是入門元素動態創建的HTML被加載後,因此jQuery的不能訪問它們。我知道如何使用jquery.on方法將事件綁定到這些元素,但我不知道如何訪問它們以檢查它們是否存在。

我在想什麼?

感謝

回答

1

下一次嘗試用更短的例子:)無論如何,我認爲你必須調用loadFeed(0, done)否則做回調後會立即

+1

THX稱爲合成的問題!我簡直不敢相信那麼簡單.. –