I get how to stub Mongoose models (thanks to Stubbing a Mongoose model with Sinon), but I don't quite understand how to stub calls like:
myModel.findOne({"id": someId})
.where("someBooleanProperty").equals(true)
...
.exec(someCallback);
I tried the following:
var findOneStub = sinon.stub(mongoose.Model, "findOne");
sinon.stub(findOneStub, "exec").yields(someFakeParameter);
to no avail, any suggestions?
If you use Promise, you can try sinon-as-promised:
sinon.stub(Mongoose.Model, 'findOne').returns({
exec: sinon.stub().rejects(new Error('pants'))
//exec: sinon.stub(). resolves(yourExepctedValue)
});
I've solved it by doing the following:
var mockFindOne = {
where: function () {
return this;
},
equals: function () {
return this;
},
exec: function (callback) {
callback(null, "some fake expected return value");
}
};
sinon.stub(mongoose.Model, "findOne").returns(mockFindOne);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With