1

我正在尝试在以下主干视图上指定单击事件处理程序:

class ItemView extends Backbone.View
  events:
    "click": "addToCurrentlyFocusedList"

  addToCurrentlyFocusedList: (e) =>
    window.currentlyFocusedList.add @model

这就是我所拥有的:

describe "ItemView", ->
  beforeEach ->
    @item = new Backbone.Model
      id: 1
      name: "Item 1"
    @view = new ItemView model: @item

  describe "when clicked", ->
    it "adds the item to the currently focused list", ->
      window.currentlyFocusedList = sinon.stub()
      window.currentlyFocusedList.add = sinon.stub()
      @view.$el.trigger "click"
      expect(window.currentlyFocusedList.add).toHaveBeenCalledWith @item

这行得通,但由于某种原因它困扰着我。也许感觉太像我在测试实现了。

我可以看到的一个可能的改进是将 click 事件处理程序、规范和 移动currentlyFocusedList到一个名为的新视图中AppView

describe "AppView", ->
  beforeEach ->
    @view = new AppView

  it "adds a clicked item to the currently focused list", ->
    $clickedItem = @view.$(".item:first")
    $clickedItem.trigger "click"
    expect(@view.currentlyFocusedList.pluck('id')).toInclude $clickedItem.attr('data-id')

很好,这也消除了window污染。它还测试该项目是否确实已添加到集合中。除此之外,移动事件处理程序和规范AppView是否比我的第一种方法更好?有没有更好的方法来解决这个问题?

4

1 回答 1

1

我会用一个虚拟集合将 window.currentlyFocusedList 存根,并测试它是否被添加到那里。这些方面的东西:

beforeEach ->
  @collection = new Backbone.Collection()
  spyOn(window, 'currentlyFocusedList').andReturn @collection

it "adds the item to the collection", ->
  @view.$el.click()
  expect(@collection).toInclude @item

这将测试您的代码实际执行的操作;将项目添加到集合中的代码如何影响视图存在于其他地方,应该在其他地方进行测试。

于 2012-04-10T01:40:00.247 回答