2017-11-25 13 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" 
}); 

}

そして今、私はジャスミンでこれをテストしようとしていますが、どういうわけか、私はそれを把握するカント:これは私が使用するコードです。私のコンテナ(クラス "フィード")に少なくとも1つのエントリ(クラス "エントリ")が追加されているかどうかを確認しようとしています。これは、私はジャスミンで使用される私のコードです:

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

次の時間が短い例:)とにかく、私はあなたがそれをすぐに

+1

Thxを呼ばれていますloadFeed(0, done)そうでない場合に行うコールバックを呼び出すために持っていることを考えると疑問を合成しよう!私はそれが単純だとは信じられない。 –

関連する問題