Backbone + Jasmine测试路由器中的AJAX成功回调

时间:2012-04-05 19:29:58

标签: ruby-on-rails backbone.js coffeescript jasmine

说我有以下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调用完成之前运行期望函数。有没有一种很好的方法来测试这样的回调?

1 个答案:

答案 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()