7

I'm trying to write a simple spec for a Backbone Todos collection which stubs the Backbone Todo model.

Here's my spec:

describe "TodoApp.Collections.Todos", ->

  beforeEach ->
    @todoStub = sinon.stub window, 'TodoApp.Models.Todo'

  afterEach ->
    @todoStub.restore()

This gives me the following error:

TypeError: Attempted to wrap undefined property TodoApp.Models.Todo as function

The Todo model is defined though as todo = new TodoApp.Models.Todo() doens't give an error.

Is it a scoping issue? Could somebody point me in the right direction?

smek
  • 1,669
  • 1
  • 17
  • 19

2 Answers2

8

I just ran into that problem too. You should call it like this...

    beforeEach ->
            @todoStub = sinon.stub window.TodoApp.Models, 'Todo'

instead of this.

    beforeEach ->
            @todoStub = sinon.stub window, 'TodoApp.Models.Todo'

this solved the problem for me

@smek: this also solves your problem from http://tinnedfruit.com/2011/03/25/testing-backbone-apps-with-jasmine-sinon-2.html

pabera
  • 1,042
  • 1
  • 13
  • 22
1

The syntax you're using sinon.stub window, 'TodoApp.Models.Todo' would be for wrapping window['TodoApp.Models.Todo'] as a function. http://sinonjs.org/docs/#stubs

With sinon you're more likely going to be wrapping a particular function on your Todo model with a stub: sinon.stub TodoApp.Models.Todo, 'Foo'.

Sinon can stub an entire object but I think it's designed to be more granular.

Eric Bock
  • 1,732
  • 1
  • 18
  • 22
  • Hi Erick, thanks for your answer. I'm trying to stub the todo model so I can test the todos collection in isolation. I'm following the example on http://tinnedfruit.com/2011/03/25/testing-backbone-apps-with-jasmine-sinon-2.html where is states you can stub the models constructor function like this. – smek Feb 22 '12 at 21:07
  • @smek have you attached your ```Todo``` model to ```window```, similar to this: http://stackoverflow.com/questions/4214731/coffeescript-global-variables ? – Eric Bock Feb 23 '12 at 16:45
  • @Erick I've defined my model with: class window.TodoApp.Models.Todo extends Backbone.Model – smek Feb 24 '12 at 09:08
  • @EricBock I have a similar requirement to stub an entire BackBone Model object using SinonJS. The link ( stub an entire object ) which you posted doesnt seem to work. Is there any other example link for the same, I tried the http://tinnedfruit.com/2011/03/25/testing-backbone-apps-with-jasmine-sinon-2.html tutorial, but getting errors like "Attempted to wrap undefined property Todo as function" – Remis Haroon - رامز Sep 14 '15 at 11:56