node.js - 用 sinon 模拟/ stub Mongoose findById

标签 node.js mongoose mocha.js sinon

我正在尝试 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/

相关文章:

php - 更改 ShareJS 中的默认文本

node.js - 使用 MEAN 和 Node Mailer 将电子邮件发送到动态发件人地址

javascript - 静态内容服务在 Express 中不起作用

javascript - Mongodb 聚合以对数组中最常见的项目进行排序?

javascript - 如何跳到下一个描述 Mocha 错误?

javascript - Chai 深平等和平等不工作

javascript - 如何为我的整个包启用严格模式但不为依赖启用?

mongodb - 如何在 Mongoose 文档中允许自由格式的 JSON 数据?

mongodb - 使用 Mongoose 指定索引名称

node.js - 如何在 describe() 的 before() block 中动态生成 Mocha 测试?