0

所以我有这个 JS 原型(类),我正在尝试为其构建 jasmine 测试,但似乎无法弄清楚如何让这些测试工作。

这是该课程的重要部分:

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 回答