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

Expecting functions to be invoked with functions as parameters

本文关键字:函数 参数 调用 期望      更新时间:2023-09-26

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

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)

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)

期望一个新的矩阵模型正在被创建。不过,其他两个规范失败的地方让我感到困惑:

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实例范围内返回的函数不同。

另外,我完全无法理解为什么@matricesView.showError在MatricesView中明确定义时未定义。

任何帮助都将非常感激。我肯定需要另一双眼睛,因为我的眼睛现在有点累了:-/

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

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

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

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

o_O

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

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

第二个更令人困惑—@matricesView.showError不可能是未定义的(您可以添加console.log来确认这一点)。所以这可能只是一个弦化问题;尝试生成一个简化的测试用例并将其发布到Jasmine问题跟踪器。但是,要使测试通过,请尝试数组包装。如果这不起作用,可能是Jasmine在测试引用相等性,而不是深度对象相等性?如果是这种情况,您可能想尝试最近添加的objectContaining匹配器。