使用样本数据测试钛合金BackboneJS Collection

时间:2013-11-12 17:41:47

标签: backbone.js coffeescript appcelerator titanium-alloy

我试图弄清楚如何使用示例数据测试Backbone.Collection,但每次我在Collection上调用fetch时,它似乎没有按照我期望的方式运行。例如,使用jasmine和coffeescript,

describe "task model", ->
  testData = [
      { id: 1, type: "personal", complete: false }
      { id: 2, type: "business", complete: true }
  ]

  collection = null
  item = null
  testTasks = Alloy.createCollection "task"

   addTask = (t) ->
     #newTask = new model t
     Ti.API.info t
     testTasks.add new Alloy.createModel "task", t
     # testTasks.length is 2 which is correct
     Ti.API.info "testTasks.length after add is #{testTasks.length}"

   # add test data to a collection to use for tests/dev
   addTask t for t in testData

   beforeEach ->
     collection = Alloy.createCollection "task", testTasks
     item = Alloy.createModel "task"
     collection.fetch view

   # fails: Expected 0 to be 2
   it "has sample data for development", ->
     collection.fetch view
     expect(collection.length).toEqual 2

我正在使用一个名为Titanium Alloy的框架,该框架正在使用BackboneJS 0.9.2

1 个答案:

答案 0 :(得分:1)

您需要等待断言,直到获取集合。

$.when( collection.fetch view).then (data, textStatus, jqXHR )->
  expect(collection.length).toEqual 2

或者

collection.fetch view,
  checkFunction = ->
    expect(collection.length).toEqual 2
  success: =>
    checkFunction()
  error: =>
    checkFunction()