我正在尝试使用 Sinon.js 来 stub 我的 Student
Mongoose 模型的模型构造函数。
var Student = require('../models/student');
var student = new Student({ name: 'test student' }); // I want to stub this constructor
查看 Mongoose 源代码,Model从 Document 继承其原型(prototype),它调用了 Document
函数,所以这就是我为了 stub 构造函数而尝试的。但是,我的 stub 永远不会被调用。
sinon.stub(Student.prototype__proto__, 'constructor', () => {
console.log('This does not work!');
return { name: 'test student' };
});
createStudent(); // Doesn't print anything
感谢您的任何见解。
编辑:
我不能直接将 Student()
设置为 stub ,因为我还在另一个测试中 stub Student.find()
。所以我的问题本质上是“如何同时 stub Student()
和 Student.find()
?”
最佳答案
这当然只能用 sinon 来完成,但这将非常依赖于库的工作方式,并且不会让人感到安全和可维护。
对于难以直接模拟的依赖项,您应该查看 rewire或 proxyquire (我使用 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...
[编辑]
"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);
关于javascript - 如何 stub Mongoose 模型构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40583465/