所以我有一个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实例,但是我不知道是怎么回事或者为什么。
如果任何人能给我帮助,我将不胜感激。
发布于 2015-12-11 09:25:03
所以我在发了这个问题几分钟后就解决了这个问题……我几乎总是这么做。
问题是我将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()https://stackoverflow.com/questions/34214488
复制相似问题