我正在尝试在以下Backbone视图中指定click事件处理程序:
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
这有效,但出于某种原因让我困扰。也许感觉太像我正在测试实现。
我可以看到的一个可能的改进是将点击事件处理程序,规范和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
比我的第一种方法更好吗?有没有更好的方法来解决这个问题?
答案 0 :(得分:1)
我会使用虚拟Collection将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
这将测试您的代码实际执行的操作;如何将项目添加到集合中的代码会影响视图生活在其他地方,并且应该在其他地方进行测试。