2012-04-07 4 views
1

私は、次のバックボーンビューのクリックイベントハンドラを仕様にしようとしています:Backboneビューイベントがコレクションにアイテムを追加することをテストするにはどうすればよいですか?

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 

これは動作しますが、それは何らかの理由で私を悩まします。私は実装をテストしているように感じるかもしれません。私が見ることができる

一つの可能​​な改善はAppViewと呼ばれる新しいビューにクリックイベントハンドラ、仕様、およびcurrentlyFocusedListが動いている:

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

主観的な質問。これはおそらくhttp://programmers.stackexchange.com/またはhttp://codereview.stackexchange.com/に属します。 –

+0

クール。私はcodereview.stackexchange.comについて知らなかった。ヒントをありがとう! – Laconical

答えて

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 

これはあなたのコードが実際に何をするかテストします。コレクションにアイテムを追加する方法のコードは、ビューの存続期間に影響し、別の場所でテストする必要があります。

関連する問題