【问题标题】:Backbone.js Parse MethodBackbone.js 解析方法
【发布时间】: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"];
    }
  });

你能告诉我我在这里做错了什么吗?

【问题讨论】:

  • 你的代码从这里看起来很棒。你能发布你的Task Backbone 模型吗?
  • @BrentAnderson 我发现了问题所在。在任务模型中,我有验证参数“attrs”的验证方法,首先检查 attrs.hasOwnProperty,然后检查条件。但是在有 null 和 undefined 的情况下它失败了。所以我添加了它们,现在测试工作正常。谢谢:)
  • @felix 您应该将您的解决方案添加为答案并将其标记为正确。

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


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2012-06-22
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多