1

I am trying to stub a mongoose model to return a json value

the code that i have is

var valueToReturn = {
                      name:'xxxxx'
                     };

var stub = sinon.stub(MyModel.prototype,'findOne');

stub.returns(valueToReturn);

I get this error : TypeError:Attempted to wrap undefined property findOne as function

Asieh hojatoleslami
  • 3,240
  • 7
  • 31
  • 45
Rahul Ganguly
  • 1,908
  • 5
  • 24
  • 36
  • Have a look [here](http://stackoverflow.com/a/28885743/1521933) – Philip O'Brien Sep 15 '15 at 10:40
  • Here they are using the findOne method of mongoose.Model. I am trying to use MyModel.findOne because my export method has findOne being used for 2 different models. So i want to try and stub 2 different models – Rahul Ganguly Sep 15 '15 at 10:49

1 Answers1

3

Take a look to sinon-mongoose. You can expects chained methods with just a few lines:

// If you are using callbacks, use yields so your callback will be called
sinon.mock(YourModel)
  .expects('findById').withArgs('abc123')
  .chain('exec')
  .yields(someError, someResult);

// If you are using Promises, use 'resolves' (using sinon-as-promised npm) 
sinon.mock(YourModel)
  .expects('findById').withArgs('abc123')
  .chain('exec')
  .resolves(someResult);

You can find working examples on the repo.

Also, a recommendation: use mock method instead of stub, that will check the method really exists on the original object.

Gon
  • 627
  • 7
  • 6
  • 1
    Are you the creator of sinon-mongoose? You plug it in 7-8 different threads about mongoose testing. – VtoCorleone May 04 '16 at 20:10
  • 1
    @VtoCorleone yes, I shared it because I think it could be useful for others facing the same problem I had when mocking mongoose models :) – Gon May 06 '16 at 19:01