【问题标题】:How to stub Mongoose model constructor如何存根猫鼬模型构造函数
【发布时间】:2017-03-27 18:41:19
【问题描述】:

我正在尝试使用 Sinon.js 来存根我的 Student Mongoose 模型的模型构造函数。

var Student = require('../models/student');

var student = new Student({ name: 'test student' }); // I want to stub this constructor

查看Mongoose源代码,ModelDocument继承其原型,它调用Document函数,所以这是我为了存根构造函数而尝试的。但是,我的存根永远不会被调用。

sinon.stub(Student.prototype__proto__, 'constructor', () => {
  console.log('This does not work!');
  return { name: 'test student' };
});

createStudent(); // Doesn't print anything

感谢您的任何见解。

编辑: 我不能直接将Student() 设置为存根,因为我还在另一个测试中存根Student.find()。所以我的问题本质上是“我如何同时存根Student()Student.find()?”

【问题讨论】:

    标签: javascript node.js mongodb mongoose sinon


    【解决方案1】:

    当然只能使用 sinon 来完成,但这将非常依赖于 lib 的工作方式,并且感觉不安全和可维护。

    对于难以直接模拟的依赖项,您应该查看 rewireproxyquire(我使用 rewire,但您可能需要选择)进行“猴子修补”。

    你会像require一样使用rewire,但它有一些糖。 示例:

    var rewire = require("rewire");
    var myCodeToTest = rewire("../path/to/my/code");
    
    //Will make 'var Student' a sinon stub.
    myCodeToTest.__set__('Student', sinon.stub().returns({ name: 'test'}));
    
    //Execute code
    myCodeToTest(); // or myCodeToTest.myFunction() etc..
    
    //assert
    expect...
    

    [编辑]

    “如何同时存根 Student() 和 Student.find()?”

    //Will make 'var Student' a sinon stub.
    var findStub = sinon.stub().returns({});
    var studentStub = sinon.stub().returns({find: findStub});
    myCodeToTest.__set__('Student', studentStub);
    

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 2015-06-20
      • 2016-01-21
      • 1970-01-01
      • 2015-05-03
      • 2011-11-24
      • 2019-09-21
      • 2020-09-05
      相关资源
      最近更新 更多