如何存根Mongoose模型的构造函数

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

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

看看Mongoose的源代码, Model从Documentinheritance它的原型,它调用了Document函数,所以这就是我为了存根构造函数而尝试的。 然而,我的存根永远不会被调用。

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

感谢您的任何见解。

编辑:我不能直接设置Student()作为存根,因为我也stub Student.find()在另一个testing。 所以我的问题基本上是“我如何同时存根Student()Student.find() ?”

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

对于难以直接模仿的依赖,你应该看看rewire或者proxyquire (我使用rewire ,但你可能想要有一个select)来做“猴子补丁”。

你会像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);