Javascript Backbone.js解析方法
我正在尝试使用以下工具对我的第一个backbone.js应用程序进行单元测试 在这个特定的测试用例中,我使用sinon.js fakeServer方法返回具有以下结构的虚拟响应Javascript Backbone.js解析方法,javascript,unit-testing,backbone.js,jasmine,sinon,Javascript,Unit Testing,Backbone.js,Jasmine,Sinon,我正在尝试使用以下工具对我的第一个backbone.js应用程序进行单元测试 在这个特定的测试用例中,我使用sinon.js fakeServer方法返回具有以下结构的虚拟响应 beforeEach( function(){ this.fixtures = { Tasks:{ valid:{ "tasks":[ { id: 4, name:'Need to complete tests',
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”键,只返回对象数组,这在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"];
}
});
你能告诉我我做错了什么吗?我的代码的问题在于模型的validate方法,而不是集合的parse方法。我在测试这些属性,即使它们不存在。发送给验证的对象不会每次都具有所有属性。例如,在具有id、标题和状态的任务模型中,如果我创建一个类似于
var t = new Task({'title':'task title'});
t.save();
这里,validate方法将只获取{'title':'task title'}作为validate方法的参数
因此,在validate方法中添加这些条件也很重要,当我添加条件以检查特定属性的存在时,以及当它不是null或未定义时,我的测试开始通过。从这里看,您的代码看起来很棒。你能发布你的
任务
主干模型吗?@BrentAnderson我发现了问题所在。在任务模型中,我使用了validate方法,该方法通过首先检查attrs.hasOwnProperty,然后检查条件来验证参数“attrs”。但在存在null和未定义的情况下,它失败了。所以我添加了它们,现在测试运行良好。谢谢:)@felix您应该添加您的解决方案作为答案,并将其标记为正确。