我正在尝试 stub 我的 Mongoose 模型,特别是 Mongoose 的 findById
方法
当使用“abc123”调用 findById 时,我试图让 mongoose 返回指定的数据
这是我目前所拥有的:
require('../../model/account');
sinon = require('sinon'),
mongoose = require('mongoose'),
accountStub = sinon.stub(mongoose.model('Account').prototype, 'findById');
controller = require('../../controllers/account');
describe('Account Controller', function() {
beforeEach(function(){
accountStub.withArgs('abc123')
.returns({'_id': 'abc123', 'name': 'Account Name'});
});
describe('account id supplied in querystring', function(){
it('should retrieve acconunt and return to view', function(){
var req = {query: {accountId: 'abc123'}};
var res = {render: function(){}};
controller.index(req, res);
//asserts would go here
});
});
我的问题是在运行 mocha 时出现以下异常
TypeError: Attempted to wrap undefined property findById as function
我做错了什么?
最佳答案
查看sinon-mongoose .您只需几行就可以期待链式方法:
// If you are using callbacks, use yields so your callback will be called
sinon.mock(YourModel)
.expects('findById').withArgs('abc123')
.chain('exec')
.yields(someError, someResult);
// If you are using Promises, use 'resolves' (using sinon-as-promised npm)
sinon.mock(YourModel)
.expects('findById').withArgs('abc123')
.chain('exec')
.resolves(someResult);
您可以在存储库中找到工作示例。
此外,建议:使用mock
方法而不是stub
,这将检查该方法是否确实存在。
关于node.js - 用 sinon 模拟/ stub Mongoose findById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22114021/