3
我想單元測試我的第一個backbone.js應用程序使用sinon.js and jasmine.js。Backbone.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"];
}
});
能否請你告訴我什麼我做錯了這裏?
你的代碼看起來不錯。你能發佈你的'任務'骨幹模型嗎? – 2012-01-28 20:18:59
@BrentAnderson我發現了什麼問題。在任務模型中,我有驗證參數'attrs'的驗證方法,首先檢查attrs.hasOwnProperty,然後檢查條件。但是在沒有定義的情況下它失敗了。所以我加了他們,現在測試工作正常。謝謝:) – felix 2012-01-29 05:27:11
@felix您應該添加您的解決方案作爲答案並將其標記爲正確。 – 2012-01-29 13:23:50