Mocko/stubing mongoose findById with sinon

Ale*_*lex 6 mocha.js mongoose node.js sinon

我试图将我的猫鼬模型,特别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
            });
    });
Run Code Online (Sandbox Code Playgroud)

我的问题是我在运行mocha时遇到以下异常

TypeError:尝试将未定义属性findById包装为函数

我究竟做错了什么?

Gon*_*Gon 3

看看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);
Run Code Online (Sandbox Code Playgroud)

您可以在存储库中找到工作示例。

另外,建议:使用mockmethod 而不是stub,这将检查该方法是否确实存在。