我试着把我的猫鼬模型,特别是猫鼬的findById
方法
当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
});
});
我的问题是,在运行mocha时,我会得到以下异常
TypeError:尝试将未定义的属性findById包装为函数
我做错了什么?
发布于 2015-11-13 07:57:02
看看西农猫鼬。只需几行代码就可以期望使用链式方法:
// 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
,这将检查方法是否真的存在。
发布于 2014-06-11 10:27:44
由于您似乎是在测试单个类,所以我将使用泛型
var mongoose = require('mongoose');
var accountStub = sinon.stub(mongoose.Model, 'findById');
这将阻止对Model.findById
修补的猫鼬的任何调用。
https://stackoverflow.com/questions/22114021
复制