【问题标题】:How to stub methods in a Mongoose model?如何在 Mongoose 模型中存根方法?
【发布时间】:2016-12-21 18:08:10
【问题描述】:

如何存根以下虚拟模式的实例方法bark

var dogSchema = mongoose.Schema({
  // ...
});

dogSchema.methods = {
  bark() { console.log('Woof!') },
};

比如我要测试下面的函数barkOne()

function barkOne() {
  Dog.findOne().exec().then(dog => dog.bark());
}

为了像这样测试它,我如何能够存根它?

describe('barkOne', () =>
  it('should make all dogs bark', () => {
    barkOne().then(() => {
      assert(barkStub.calledOnce);
    });
  })
});

谢谢!

【问题讨论】:

    标签: javascript node.js mongoose sinon stub


    【解决方案1】:

    从 mongoose 4.4.5 开始,我可以使用 Model.prototype 存根方法。例如

    const stub = sandbox.stub(Dog.prototype, 'bark');
    
    Dog.findOne().exec().then(dog => {
      // dog[0].bark === stub
    })
    

    【讨论】:

    • 你从哪里得到的沙盒?是诗乃的吗?
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 2011-11-17
    • 2014-04-15
    • 2012-09-07
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多