繁体   English   中英

Jasmine 监视不存在的对象

[英]Jasmine spies on nonexistent objects

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

index: ->
  @collection = new App.Collections.ThingsCollection()
  @collection.fetch success: ->
    # ...

我正在尝试使用如下所示的测试来测试这个 function 和 Jasmine:

it 'fetches the collection from the server', ->
  @router.index()
  expect(@router.collection.fetch).toHaveBeenCalled()

尝试为@router.collection.fetch()创建间谍时会遇到困难。 因为@router.collection在实际调用@router.index() function 之前不存在,所以我无法创建这样的间谍...

@fetchStub = spyOn(@router.collection, 'fetch')

...因为@router.collection还不存在。 我没有将@collection的构造放在initialize() function 中,因为对于不使用它的函数(例如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()

那么,在您before的 function 中:

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

这里有更多相关信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM