Question

I'm trying to stub my mongoose model, specifically the findById method of mongoose

I'm trying to make mongoose return the specified data, when findById is called with 'abc123'

Here's what I have so far:

require('../../model/account');

sinon = require('sinon'),
mongoose = require('mongoose'),
accountStub = sinon.stub(mongoose.model('Account').prototype, 'findById');
controller = require('../../controllers/account');

describe('Account Controller', function() {

    beforeEach(function(){
        accountStub.withArgs('abc123')
            .returns({'_id': 'abc123', 'name': 'Account Name'});
    });

    describe('account id supplied in querystring', function(){
        it('should retrieve acconunt and return to view', function(){
            var req = {query: {accountId: 'abc123'}};
            var res = {render: function(){}};

            controller.index(req, res);
                //asserts would go here
            });
    });

My problem is that I am getting the following exception when running mocha

TypeError: Attempted to wrap undefined property findById as function

What am I doing wrong?

Was it helpful?

Solution

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.

OTHER TIPS

Since it seems you are testing a single class, I'd roll with the generic

var mongoose = require('mongoose');
var accountStub = sinon.stub(mongoose.Model, 'findById');

This will stub any calls to Model.findById patched by mongoose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top