Javascript 茉莉花窥探不存在的物体

Javascript 茉莉花窥探不存在的物体,javascript,backbone.js,coffeescript,jasmine,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.collect

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

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.index()
函数之前,
@router.collection
不存在,所以我无法创建这样的间谍

@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()

那么,在您的
before
功能中:

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

还有更多相关信息。

@router.collection
将在
index()
函数中重新创建,因此这实际上不会起任何作用。感谢您的更新,@clem!