茉莉花间谍不存在的物体

时间:2012-04-05 17:34:33

标签: javascript backbone.js coffeescript jasmine

我有一个骨干路由器,它具有以下操作:

index: ->
  @collection = new App.Collections.ThingsCollection()
  @collection.fetch success: ->
    # ...

我正在尝试使用Jasmine测试此函数,使用如下所示的测试:

it 'fetches the collection from the server', ->
  @router.index()
  expect(@router.collection.fetch).toHaveBeenCalled()

尝试为@router.collection.fetch()创建间谍时发生困难。因为@router.collection在实际调用@router.index()函数之前不存在,所以我不能像这样创建一个间谍......

@fetchStub = spyOn(@router.collection, 'fetch')

...因为@router.collection尚不存在。我没有将@collection的构造放在initialize()函数中,因为对于不使用它的函数,例如new()似乎没有必要。可能有一个众所周知的解决方案,但我一直找不到。任何帮助将不胜感激。

更新

到目前为止,这是我解决它的方法,但更优雅的解决方案会很好。

  initialize: ->
    @collection = new App.Collections.ThingsCollection()

  index: ->
    if @collection.models.length > 0
      # Assumes @collection.fetch() has already been called (i.e. switching between actions)
      view = new App.Views.ThingsIndex(collection: @collection)
      $('#app-container').html(view.render().el)
    else
      # Assumes @collection.fetch() has not been called (i.e. a new page view or refresh)
      that = this
      @collection.fetch success: ->
        view = new App.Views.ThingsIndex(collection: that.collection)
        $('#app-container').html(view.render().el)

这样我就可以拥有以下规范:

describe 'App.Routers.ThingsRouter', ->
  beforeEach ->
    @router = new App.Routers.ThingsRouter
    @fetchStub = spyOn(@router.collection, 'fetch')

  it 'fetches the collection from the server', ->
    @router.index()
    expect(@fetchStub).toHaveBeenCalled()

1 个答案:

答案 0 :(得分:0)

before函数中

@router.collection = new App.Collections.ThingsCollection()

还有更多相关信息here