Using Sinon to stub chained Mongoose calls

大憨熊 提交于 2019-12-30 04:12:12

问题


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?


回答1:


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



回答2:


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.




回答3:


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



回答4:


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



回答5:


I use promises with Mongoose and stub the methods like this:

const stub = sinon.stub(YourModel, 'findById').returns({
    populate: sinon.stub().resolves(document)
})

Then I can call it like:

const document = await YourModel.findById.populate('whatever');


来源:https://stackoverflow.com/questions/27847377/using-sinon-to-stub-chained-mongoose-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!