gpt4 book ai didi

testing - 如何测试 Backbone View 事件是否将项目添加到集合中?

转载 作者:行者123 更新时间:2023-11-28 20:45:57 25 4
gpt4 key购买 nike

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

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 的新 View 中:

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 中是否比我的第一种方法更好?有没有更好的方法来解决这个问题?

最佳答案

我会用一个虚拟集合来 stub 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

这会测试您的代码实际做了什么;将项目添加到集合如何影响 View 的代码存在于其他地方,应该在其他地方进行测试。

关于testing - 如何测试 Backbone View 事件是否将项目添加到集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10058830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com