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