如何存根猫鼬模型构造函数

How to stub Mongoose model constructor

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

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

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

查看 Mongoose 源代码,Model inherits its prototype from Document, which calls the 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()。所以我的问题本质上是 "how do I stub Student() and Student.find() at the same time?"

这肯定只能用 sinon 来完成,但这将非常依赖于库的工作方式,并且不会让人感到安全和可维护。

对于难以直接模拟的依赖项,你应该看看rewire or proxyquire(我使用rewire,但你可能想有一个选择)做"monkey patching"。

您将像 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...

[编辑]

"how do I stub Student() and Student.find() at the same time?"

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