1

我正在使用以下 Coffeescript 代码来验证一个主干.js 视图的初始化是否构造了另一个:

describe 'Avia.AviaView', ->

  beforeEach ->
    @aviaView = new Avia.AviaView(addFixtureDiv('avia'))
    @matricesView = new Backbone.View()

    spyOn(Avia, 'MatricesView').andCallFake(
      (element) =>
        if !element
          throw "Expected MatricesView to be constructed with a parent element"
        else if element.attr('id') != 'tabs-3'
          throw "Expected MatricesView to be constructed with the parent element #tabs-3"
        else
          @matricesView
    )

  describe 'initialize', ->

    beforeEach ->
      @aviaView.initialize()

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

这很好用,但我不禁认为应该可以改进它。我在想像这样的语法:

it 'creates a new MatricesView ', ->
  expect(Avia.MatricesView).toHaveBeenCalledMatching((args...) => args[0].attr('id') == 'tabs-3')

... wheretoHaveBeenCalledMatching接受一个函数,该函数接受一些参数,并返回真值表示成功,否则返回假值。

有没有人遇到过这样的事情,还是我需要在这里自己动手?或者,有没有人更好地建议如何改进此代码?

4

1 回答 1

1

toHaveBeenCalledWith ()不适合你吗?在大多数情况下,您要么提前知道这些值,要么可以计算它们。

如果您确实需要使用函数来评估调用的参数,您可以使用单独的期望和argsForCall来单独测试每个参数。

如果最坏的情况发生,您总是可以编写自己的匹配器。但这听起来比前两个要难得多:)

于 2011-12-08T04:48:20.430 回答