2017-11-25 123 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称为合成的问题!我简直不敢相信那么简单.. –