使用Sinon存根链接mongoose电话
我得到如何将Mongoose模型存储(感谢用Sinon存储Mongoose模型 ),但是我不太明白如何存储调用,如:
myModel.findOne({"id": someId}) .where("someBooleanProperty").equals(true) ... .exec(someCallback);
我尝试了以下内容:
var findOneStub = sinon.stub(mongoose.Model, "findOne"); sinon.stub(findOneStub, "exec").yields(someFakeParameter);
无济于事,有什么build议?
我已经通过执行以下操作来解决它:
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);
看一下sinon-mongoose 。 你可以期待只用几行链接的方法:
sinon.mock(YourModel).expects('findOne') .chain('where').withArgs('someBooleanProperty') .chain('exec') .yields(someError, someResult);
你可以找回工作的例子。
此外,build议:使用mock
方法而不是stub
,这将检查方法确实存在。
如果你使用Promise,你可以尝试sinon-as-promise :
sinon.stub(Mongoose.Model, 'findOne').returns({ exec: sinon.stub().rejects(new Error('pants')) //exec: sinon.stub(). resolves(yourExepctedValue) });
另一种方法是对创build的查询(使用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);