Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Sinon to stub chained Mongoose calls

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?

like image 209
Nepoxx Avatar asked Jan 08 '15 18:01

Nepoxx


2 Answers

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)
});
like image 119
Ping.Goblue Avatar answered Sep 21 '22 09:09

Ping.Goblue


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);
like image 22
Nepoxx Avatar answered Sep 20 '22 09:09

Nepoxx