【问题标题】:Using Sinon to stub a mongoose model使用 Sinon 对 mongoose 模型进行 stub
【发布时间】:2015-12-11 13:41:38
【问题描述】:

我正在尝试存根猫鼬模型以返回 json 值

我的代码是

var valueToReturn = {
                      name:'xxxxx'
                     };

var stub = sinon.stub(MyModel.prototype,'findOne');

stub.returns(valueToReturn);

我收到此错误:TypeError:Attempted to wrap undefined property findOne as function

【问题讨论】:

  • 看看here
  • 这里他们使用的是 mongoose.Model 的 findOne 方法。我正在尝试使用 MyModel.findOne,因为我的导出方法已将 findOne 用于 2 个不同的模型。所以我想尝试存根 2 个不同的模型

标签: node.js mongoose tdd 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,这将检查该方法是否确实存在于原始对象上。

【讨论】:

  • 你是sinon-mongoose的创造者吗?您将其插入 7-8 个关于猫鼬测试的不同线程中。
  • @VtoCorleone 是的,我分享了它,因为我认为它可能对其他面临我在模拟猫鼬模型时遇到的同样问题的人有用:)
猜你喜欢
  • 2012-07-04
  • 2018-07-19
  • 2015-03-30
  • 2017-07-11
  • 2023-04-01
  • 2019-09-26
  • 1970-01-01
  • 2015-08-21
相关资源
最近更新 更多