次のアクションを持つバックボーンルーターがあります。
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()