javascript - 如何 stub Mongoose 模型构造函数

标签 javascript node.js mongodb mongoose sinon

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

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

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

查看 Mongoose 源代码,ModelDocument 继承其原型(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 来完成,但这将非常依赖于库的工作方式,并且不会让人感到安全和可维护。

对于难以直接模拟的依赖项,您应该查看 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...

[编辑]

"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/

相关文章:

javascript - 如何从给定对象以指定方式获取构造对象

node.js - 你能用jade只渲染你的html的动态部分...而不弄乱你的html的其余部分吗

MongoDB多维数组投影

mongodb - Mongodb中匹配子文档的批量更新数组

linux - Windows 10 Linux 子系统。如何安装 MongoDB

javascript - 如何在通话时交换 webrtc 中的摄像头源(javascript API)

javascript - 如何修改数据列表元素或替代

javascript - Jquery ajax 与 XMLHttpRequest

javascript - 我想停止提交整个页面并使用 javascript 仅提交我的表单

javascript - jQuery 和 Express - 混淆了成功和错误