Backbone.js解析方法

时间:2012-01-28 19:18:55

标签: javascript unit-testing backbone.js jasmine sinon

我正在尝试使用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'键并仅返回对象数组,这在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"];
    }
  });

请告诉我,我在这里做错了什么?

1 个答案:

答案 0 :(得分:-1)

我的代码的问题出在模型的validate方法中,而不是集合的parse方法。我正在测试属性,即使它们不存在。发送到validate的对象不会每次都具有所有属性。例如,在具有id,title和status的任务模型中,默认情况下status设置为0,如果我创建类似

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

这里,validate方法只会将{'title':'task title'}作为validate方法的参数。

因此,在validate方法中添加这些条件也很重要,当我添加条件以检查是否存在特定属性时,以及当它不为null或未定义时,我的测试开始传递。