2012-01-28 75 views
3

我想單元測試我的第一個backbone.js應用程序使用sinon.js and jasmine.jsBackbone.js解析方法

在這個特殊的測試案例中,我使用了sinon.js fakeServer方法來返回一個具有以下結構的虛擬響應。

beforeEach(function(){ 
    this.fixtures = { 
    Tasks:{ 
     valid:{ 
     "tasks":[ 
      { 
      id: 4, 
      name:'Need to complete tests', 
      status: 0 
      }, 
      { 
      id: 2, 
      name:'Need to complete tests', 
      status: 1 
      }, 
      { 
      id: 3, 
      name:'Need to complete tests', 
      status: 2, 
      } 
     ] 
     } 
    } 
    }; 
    }); 

所以當我在下面的測試用例中實際調用fetch調用時,它會正確返回3個模型。在集合的解析方法中,我試圖刪除root的'tasks'鍵,只是返回backbone.js文檔中提到的單獨的對象數組。但是,當我這樣做,沒有模型被添加到該集合和collection.length返回0

describe("it should make the correct request", function(){ 

    beforeEach(function(){ 
     this.server = sinon.fakeServer.create(); 
     this.tasks = new T.Tasks(); 
     this.server.respondWith('GET','/tasks', this.validResponse(this.fixtures.Tasks.valid)); 
    }); 

    it("should add the models to the tasks collections", function(){ 
     this.tasks.fetch(); 
     this.server.respond(); 
     expect(this.tasks.length).toEqual(this.fixtures.Tasks.valid.tasks.length); 
    }); 

    afterEach(function() { 
     this.server.restore(); 
    }); 

    }); 

任務收集

T.Tasks = Backbone.Collection.extend({ 
    model: T.Task, 
    url:"/tasks", 
    parse: function(resp, xhr){ 
     return resp["tasks"]; 
    } 
    }); 

能否請你告訴我什麼我做錯了這裏?

+0

你的代碼看起來不錯。你能發佈你的'任務'骨幹模型嗎? – 2012-01-28 20:18:59

+0

@BrentAnderson我發現了什麼問題。在任務模型中,我有驗證參數'attrs'的驗證方法,首先檢查attrs.hasOwnProperty,然後檢查條件。但是在沒有定義的情況下它失敗了。所以我加了他們,現在測試工作正常。謝謝:) – felix 2012-01-29 05:27:11

+0

@felix您應該添加您的解決方案作爲答案並將其標記爲正確。 – 2012-01-29 13:23:50

回答

-1

我的代碼的問題是在模型的驗證方法中,而不是集合的解析方法。即使它們不存在,我也在測試屬性。發送到驗證的對象不會每次都具有所有的屬性。例如,在與ID,標題和狀態,在狀態的默認設置爲0,如果我創建像

var t = new Task({'title':'task title'}); 
t.save(); 

這裏的模型任務模型,驗證方法只會得到{「標題」:」任務標題'}作爲驗證方法的參數。

因此,在validate方法中添加這些條件非常重要,並且當我添加條件來檢查特定屬性的存在以及它何時不爲null或未定義時,我的測試開始傳遞。