【问题标题】:Jasmine spies on nonexistent objects茉莉花窥探不存在的物体
【发布时间】:2012-04-19 11:11:41
【问题描述】:

我有一个具有以下操作的骨干路由器:

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

【问题讨论】:

  • 感谢您的更新,@clem!

标签: javascript backbone.js coffeescript jasmine


【解决方案1】:

怎么样,在你的before 函数中:

@router.collection = new App.Collections.ThingsCollection()

还有更多相关信息here

【讨论】:

  • @router.collectionindex() 函数中重新创建,所以这实际上不会做任何事情。
猜你喜欢
  • 1970-01-01
  • 2020-09-09
  • 2014-12-12
  • 2017-06-11
  • 1970-01-01
  • 2018-02-22
  • 2015-07-26
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多