【问题标题】:Mocking / stubbing mongoose findById with sinon用 sinon 模拟/存根猫鼬 findById
【发布时间】:2014-04-02 13:38:35
【问题描述】:

我正在尝试存根我的猫鼬模型,特别是猫鼬的findById 方法

当 findById 使用 'abc123' 调用时,我正在尝试让 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: 试图将未定义的属性 findById 包装为函数

我做错了什么?

【问题讨论】:

    标签: node.js mongoose mocha.js sinon


    【解决方案1】:

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

    您可以在 repo 上找到工作示例。

    另外,一个建议:使用mock 方法而不是stub,这将检查该方法是否真的存在。

    【讨论】:

    • 可以在示例中添加更多内容,展示如何取回模拟数据?就用户的要求而言,答案似乎不完整。
    • @lostintranslation 模拟数据将是“yield”和“resolves”上的“someResult”参数。
    【解决方案2】:

    由于您似乎正在测试单个类,所以我会使用泛型

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

    这将存根对Model.findById 的任何调用,并修补by mongoose

    【讨论】:

      猜你喜欢
      • 2016-04-09
      • 1970-01-01
      • 2017-04-26
      • 2016-01-21
      • 2019-02-08
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多