0

I am trying to figure out how to test a Backbone.Collection using sample data but every time I call fetch on the Collection it does not seem to behave the way I expect it to. For example, using jasmine and 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

I am using a framework called Titanium Alloy which is using BackboneJS 0.9.2

Peter
  • 4,493
  • 6
  • 41
  • 64

1 Answers1

1

You need to wait with your assertion until the collection is fetched.

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

Or

collection.fetch view,
  checkFunction = ->
    expect(collection.length).toEqual 2
  success: =>
    checkFunction()
  error: =>
    checkFunction()
Boti
  • 3,275
  • 1
  • 29
  • 54
  • Hi Boti. Sorry I thought that fixed my problem but I don't seem to be getting a callback at all – Peter Nov 15 '13 at 16:53
  • I have tried running `collection.fetch view, success: => Ti.API.warn "this is a test"` and `collection.fetch {view: "default", success: => Ti.API.warn "this is a test"}` and none of the callbacks seem to be firing – Peter Nov 15 '13 at 17:20