0

したがって、ジャスミンテストを構築しようとしているこのJSプロトタイプ(クラス)があり、これらのテストを機能させる方法を理解できないようです。

クラスの重要な部分は次のとおりです。

class Calendar extends BasicView
  initialize: (options) ->
    this.$el = options.el
    {@sidebar} = options
    this.$('.select-day').click this.display_date

    this

  display_date: (e) =>
    console.log 'display_date called' # <~~ this is printing
    ... do stuff ...

そして私が書いているテスト:

describe "Calendar", ->
  calendar = null

  beforeEach ->
    loadFixtures "calendar/calendar.html"

  describe "#initialize", ->
    beforeEach ->
      calendar = new Calendar().initialize
        el: $('.event-calendar')
        # just mocking dependency class
        sidebar: jasmine.createSpyObj(CurrentlyViewing, ["$"])

    it "listens for click event on .select-day", ->
      spyOn(calendar, 'display_date')
      calendar.$('.select-day:eq(1)').trigger 'click'
      expect(calendar.display_date).toHaveBeenCalled()

テストを実行するExpected spy display_date to have been called.と、実際のメソッドが呼び出されているにもかかわらず取得されます。私がスパイしているのはCalendar、私が初期化したインスタンスではないということはわかっていますが、その方法や理由はわかりません。

誰でも私にできる助けをいただければ幸いです。

4

1 に答える 1

0

だから私は質問を投稿してから20分以上後にこれを理解しました...私はほとんどいつもそうしています。

問題は、calendar変数をに設定しnew Calendar().initialize(...)てからスパイしていたことです(推測)。実際に動作するのは次のとおりです。

describe "Calendar", ->
  calendar = null

  beforeEach ->
    loadFixtures "calendar/calendar.html"
    calendar = new Calendar()
    spyOn calendar, 'display_date'

  describe "#initialize", ->
    beforeEach ->
      calendar.initialize
        el: $('.event-calendar')
        sidebar: jasmine.createSpyObj(CurrentlyViewing, ["$"])

    it "listens for click event on .select-day", ->
      calendar.$('.select-day:eq(1)').trigger 'click'
      expect(calendar.display_date).toHaveBeenCalled()
于 2015-12-11T01:25:02.980 に答える