I am trying to test that a view method gets called when my model triggers an event. But this isn't working - and I have run out of ideas why this would be. Here's the code that isn't working:
View:
class View extends Backbone.View
initialize: ->
@.listenTo @model, 'request', @disableForm, @
disableForm: ->
console.log 'disableForm'
Jasmine Test:
describe "AJAX events", ->
it "when starting an AJAX request, disable the form", ->
model = new Backbone.Model()
view = new Backbone.View( { model: model })
view.render()
spyOn(view, 'disableForm')
view.delegateEvents()
model.trigger 'request'
expect(view.disableForm).toHaveBeenCalled()
This code works in the browser fine.
Also - the console.log does print 'disableForm' when I run the tests - so the model event is triggering the call to disableForm, but my spy is not picking this up (my expectation fails). I have tried putting it into a waitsFor method, but his too did not make a difference.
Any ideas where I am going wrong?
The problem is that spyOn
will replace the function disableForm
in your view with a spy
function. But at this time the model was bound to the original function, so replacing the function in the view has no effect on the function that was bound to the event listener. When you trigger the event on the model the original function will be called and not the spy.