说我有以下Backbone路由器:
class App.Routers.ThingsRouter extends Backbone.Router
initialize: -> new App.Collections.ThingsCollection()
index: ->
that = this
@collection.fetch success: ->
view = new App.Views.ThingsIndex(collection: that.collection)
$('#app-container').html(view.render().el)
我需要写一个可以观察这个并确保调用App.Views.ThingsIndex()
的Jasmine间谍。但是,由于它是AJAX,以下方法不起作用:
describe 'index', ->
@router = new App.Routers.ThingsRouter()
spyOn(@router.collection, 'fetch')
fake = { render: -> '' }
@previewsIndexStub = spyOn(Periscope.Views, 'PreviewsIndex').andReturn(fake)
@router.index()
expect(@previewsIndexStub).toHaveBeenCalled()
因为Jasmine在AJAX调用完成之前运行期望函数。有没有一种很好的方法来测试这样的回调?
答案 0 :(得分:1)
使用内置waitsFor& amp;中的jasmines运行方法,以便在执行expect函数之前等待ajax调用完成。有关这两个功能的文档,请参阅Jasmine - Asynchronous specs。
describe 'index', ->
@router = new App.Routers.ThingsRouter()
spyOn(@router.collection, 'fetch')
fake = {}; fake.render = -> '';
@previewsIndexStub = spyOn(Periscope.Views, 'PreviewsIndex').andReturn(fake)
@router.index()
waitsFor => @previewsIndexStub.wasCalled
###
Or if you want to wait for the method to be called more than once
use form waitsFor => @previewsIndexStub.callCount > 1
###
runs => expect(@previewsIndexStub).toHaveBeenCalled()