首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用sinon嘲弄/顽固不化猫鼬findById

用sinon嘲弄/顽固不化猫鼬findById
EN

Stack Overflow用户
提问于 2014-03-01 03:54:11
回答 2查看 4K关注 0票数 6

我试着把我的猫鼬模型,特别是猫鼬的findById方法

当findById被用'abc123‘调用时,我试图让猫鼬返回指定的数据

到目前为止,我的情况如下:

代码语言:javascript
运行
AI代码解释
复制
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包装为函数

我做错了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-13 07:57:02

看看西农猫鼬。只需几行代码就可以期望使用链式方法:

代码语言:javascript
运行
AI代码解释
复制
// 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,这将检查方法是否真的存在。

票数 2
EN

Stack Overflow用户

发布于 2014-06-11 10:27:44

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

代码语言:javascript
运行
AI代码解释
复制
var mongoose = require('mongoose');
var accountStub = sinon.stub(mongoose.Model, 'findById');

这将阻止对Model.findById修补的猫鼬的任何调用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22114021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档