【问题标题】:Backbone + Jasmine testing AJAX success callback in routerBackbone + Jasmine 在路由器中测试 AJAX 成功回调
【发布时间】:2012-04-19 13:27:06
【问题描述】:

假设我有以下主干路由器:

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)

我需要编写一个 Jasmine 间谍来监视这个并确保调用 App.Views.ThingsIndex()。但是,由于它是 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 调用完成之前运行了期望函数。有没有像这样测试回调的好方法?

【问题讨论】:

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


    【解决方案1】:

    使用 jasmines 内置的 waitsFor & 运行方法,以便在执行期望函数之前等待 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()
    

    【讨论】:

    • 不知道这是否有效,因为 @previewsIndexStub 没有像 expect(@previewsIndexStub) 那样可用的 toHaveBeenCalled() 函数。我得到'undefined' is not a function
    • @clem 我的错,你会想改用变量wasCalled
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2015-02-15
    • 2013-07-14
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多