我有一个具有以下操作的骨干路由器:
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()