Mocking / stubbing mongoose findById with sinon Mocking / stubbing mongoose findById with sinon mongoose mongoose

Mocking / stubbing mongoose findById with sinon


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 calledsinon.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.


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.