0

I am writing a jasmine spec against my backbone app. However, I got stuck with this problem. Not sure why my spy function doesn't get invoked. I want to make sure when the model is changed, it should call #render.

Here is my backbone view:

class App.Views.Main extends Backbone.View
  initialize: () ->
    @model.on("change", @render, this)

  render: () ->
    console.log('rendering')
    return

Here is my jasmine spec:

it "should render when change is triggered", ->
  renderSpy = sinon.spy(@view, 'render')
  @view.model.trigger('change')

  expect(renderSpy.called).toBeTruthy()

Another thing that confuses me is that when this spec runs, it actually invokes the original method. The console log is always displayed. Anyone could help me?

Updated:

As answered below by Leonardo, I make changes with the following changes:

it "should render when reset is triggered", ->
  renderSpy = sinon.spy(App.Views.Main.prototype, 'render')
  @view.model.trigger('change')

  expect(@renderSpy.called).toBeTruthy()
  renderSpy.restore()

It works, but the problem is that it invokes the original method. I just wonder why?

Chamnap
  • 4,666
  • 2
  • 34
  • 46
  • possible duplicate of [Why is this sinon spy not being called when I run this test?](http://stackoverflow.com/questions/8441612/why-is-this-sinon-spy-not-being-called-when-i-run-this-test) – mu is too short Oct 21 '12 at 03:38

1 Answers1

1

I think this is the same that is happenning here:

https://stackoverflow.com/a/9012788/603175

Basically, you need to create the spy before you execute the constructor that executes the event listening, which binds the function to 'this' context.

Community
  • 1
  • 1
  • just wonder why it still invoke the original method? Anyway not to run it? – Chamnap Oct 21 '12 at 03:56
  • It invokes the original method because that's the reference it saves in the bindings list when you call the 'on' method. You need to replace the render function before that gets called so that methods stores the correct reference. – Leonardo Garcia Crespo Oct 21 '12 at 04:33
  • I just updated my question. Please, have a look. :) It contains the code that I have changed. – Chamnap Oct 21 '12 at 05:21