使用Sinon对Mongoose模型进行存根 [英] Stubbing a Mongoose model using Sinon
问题描述
我正在尝试对这个对象中使用的猫鼬依赖项进行存根:
I am trying to stub the mongoose dependency used in this object:
var Page = function(db) {
var mongoose = db || require('mongoose');
if(!this instanceof Page) {
return new Page(db);
}
function save(params) {
var PageSchema = mongoose.model('Page');
var pageModel = new PageSchema({
...
});
pageModel.save();
}
Page.prototype.save = save;
}
module.exports = Page;
使用这个问题的答案,我已经尝试过这样做:
Using the answer for this question, I've tried doing this:
mongoose = require 'mongoose'
sinon.stub mongoose.Model, 'save'
但是我得到了错误:
TypeError:尝试包装未定义的属性另存为函数
我也尝试过:
sinon.stub PageSchema.prototype, 'save'
然后我得到了错误:
TypeError:应该包装对象的属性
有人可以帮忙吗?我在做什么错了?
Can anyone help with this? What am I doing wrong?
推荐答案
我已经分析了猫鼬的来源,并且认为这是不可能的.保存功能未在模型上定义,而是由 hooks npm 动态生成的,它启用了
I've analysed mongoose source and don't think this is possible. Save function is not defined on model, but dynamically generated by hooks npm which enables pre/post middleware functionality.
但是,您可以像这样存根保存实例:
However, you can stub save on instance like this:
page = new Page();
sinon.stub(page, 'save', function(cb){ cb(null) })
更新:存根pageModel
UPDATE: Stubbing out pageModel
首先,需要通过将pageModel
设置为Page
(this.pageModel = xxx
)的自身属性来使其可访问.然后,您可以像下面显示的那样存根:
First, you need to make pageModel
accessible by setting it as own property of Page
(this.pageModel = xxx
). Then, you can stub it like shown bellow:
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
mongoose.set('debug', true);
schema = new mongoose.Schema({title: String});
mongoose.model('Page', schema);
var Page = function(db) {
var mongoose = db || require('mongoose');
if(!this instanceof Page) {
return new Page(db);
}
var PageSchema = mongoose.model('Page');
this.pageModel = new PageSchema();
function save(params, cb) {
console.log("page.save");
this.pageModel.set(params);
this.pageModel.save(function (err, product) {
console.log("pageModel.save");
cb(err, product);
});
}
Page.prototype.save = save;
};
page = new Page();
sinon = require('sinon');
sinon.stub(page.pageModel, 'save', function(cb){
cb("fake error", null);
});
page.save({ title: 'awesome' }, function (err, product) {
if(err) return console.log("ERROR:", err);
console.log("DONE");
});
这篇关于使用Sinon对Mongoose模型进行存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!