Using Sinon to stub chained Mongoose calls

Nepoxx picture Nepoxx · Jan 8, 2015 · Viewed 8.5k times · Source

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?

Answer

Nepoxx picture Nepoxx · Mar 5, 2015

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);