Using Sinon to stub chained Mongoose calls
Take a look to sinon-mongoose. You can expects chained methods with just a few lines:
sinon.mock(YourModel).expects('findOne') .chain('where').withArgs('someBooleanProperty') .chain('exec') .yields(someError, 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.
Another way is to stub or spy the prototype functions of the created Query (using sinon):
const mongoose = require('mongoose');sinon.spy(mongoose.Query.prototype, 'where');sinon.spy(mongoose.Query.prototype, 'equals');const query_result = [];sinon.stub(mongoose.Query.prototype, 'exec').yieldsAsync(null, query_result);