期望使用函数作为参数调用函数

时间:2011-12-07 07:50:12

标签: javascript coffeescript jasmine

我有一套相当简单的骨干视图规范:

describe 'Avia.MatricesView', ->

  beforeEach ->
    @model = {
      bind: ->
      fetch: ->
    }
    spyOn(Avia, 'Matrices').andReturn(@model)
    @matricesView = new Avia.AviaView(addFixtureDiv('fixture'))

  describe 'initialization', ->

    beforeEach ->
      spyOn(@model, 'bind')
      spyOn(@model, 'fetch')
      @matricesView.initialize()

    it 'creates a new Matrices model', ->
      expect(Avia.Matrices).toHaveBeenCalledOnce()

    it 'binds the model change event to render', ->
      expect(@model.bind).toHaveBeenCalledWith('change', @matricesView.render)

    it 'fetches the model data', ->
      expect(@model.fetch).toHaveBeenCalledWith(success: @matricesView.render, error: @matricesView.showError)

MatricesView就像规范所期望的那样:

initialize: =>
  @model = new Avia.Matrices()
  @model.bind('change', @render)
  @model.fetch(success: @render, error: @showError)

showError: =>
  alert('An error occurred while fetching data from the server.')

render: =>
  html = JST['views/matrices_view_template']()
  @el.html(html)

期望创建新的Matrices模型。然而,其他两个规格失败了,让我感到困惑:

Avia.MatricesView initialization binds the model change event to render. (/home/duncan/avia/spec/javascripts/views/matrices_view_spec.js.coffee:21)
  Expected spy bind to have been called with [ 'change', Function ] but was called with [ [ 'change', Function ] ] (line ~22)
    expect(this.model.bind).toHaveBeenCalledWith('change', this.matricesView.render);

Avia.MatricesView initialization fetches the model data. (/home/duncan/avia/spec/javascripts/views/matrices_view_spec.js.coffee:24)
  Expected spy fetch to have been called with [ { success : Function, error : undefined } ] but was called with [ [ { success : Function, error : Function } ] ] (line ~25)
    expect(this.model.fetch).toHaveBeenCalledWith({

据我所知,Jasmine认为@matricesView.render在规范范围内返回的函数与@render在MatricesView实例范围内返回的函数不同。

另外,我完全不明白为什么{MavericesView中明确定义了@matricesView.showError未定义。

非常感谢任何帮助。我当然需要第二双眼睛,因为我现在有点厌倦了: - /

2 个答案:

答案 0 :(得分:1)

是的,我现在真的很尴尬。早上用一双新眼睛看着这个:

@matricesView = new Avia.AviaView(addFixtureDiv('fixture')) 

......本来应该......

@matricesView = new Avia.MatricesView(addFixtureDiv('fixture')) 

测试应该失败,因为我实际上是在测试错误的类。

O_O

答案 1 :(得分:0)

第一次失败的测试似乎与此问题有关:https://github.com/pivotal/jasmine/issues/45尝试将参数包装在数组中:

expect(@model.bind).toHaveBeenCalledWith(['change', @matricesView.render])

第二个更令人困惑 - 没有办法@matricesView.showError未定义(你可以投入console.log来确认这一点)。所以这可能只是一个字符串化问题;尝试生成一个简化的测试用例并发布到Jasmine问题跟踪器。但是,只要让测试通过,尝试数组包装。如果这不起作用,是不是Jasmine正在测试参考平等而不是深层对象平等?如果是这种情况,您可能需要尝试最近添加的objectContaining匹配器。