【发布时间】:2012-02-21 07:12:26
【问题描述】:
我正在尝试使用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 个模型。在集合的 parse 方法中,我尝试删除根 'tasks' 键并仅返回对象数组,这在主干.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"];
}
});
你能告诉我我在这里做错了什么吗?
【问题讨论】:
-
你的代码从这里看起来很棒。你能发布你的
TaskBackbone 模型吗? -
@BrentAnderson 我发现了问题所在。在任务模型中,我有验证参数“attrs”的验证方法,首先检查 attrs.hasOwnProperty,然后检查条件。但是在有 null 和 undefined 的情况下它失败了。所以我添加了它们,现在测试工作正常。谢谢:)
-
@felix 您应该将您的解决方案添加为答案并将其标记为正确。
标签: javascript unit-testing backbone.js jasmine sinon