用sin子嘲笑/ st住mongoosefindById

我试图把我的mongoose模型,特别是mongoose的findById方法

我试图让mongoose返回指定的数据,当调用findById'abc123'

以下是我到目前为止:

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

我的问题是,我运行摩卡时得到以下exception

TypeError:试图包装未定义的属性findById作为函数

我究竟做错了什么?

看一下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); 

你可以找回工作的例子。

此外,build议:使用mock方法而不是stub ,这将检查方法确实存在。

既然看起来你正在testing一个class级,那么我就会select通用的

 var mongoose = require('mongoose'); var accountStub = sinon.stub(mongoose.Model, 'findById'); 

这将保留任何对mongoose修补的 Model.findById调用。