对猫鼬模型的虚拟属性进行存根 [英] Stubbing virtual attributes of Mongoose model
问题描述
是否可以对猫鼬模型的虚拟属性进行存根?
Is there a way to stub a virtual attribute of a Mongoose Model?
假定Problem
是模型类,并且difficulty
是虚拟属性. delete Problem.prototype.difficulty
返回false,并且该属性仍然存在,因此我无法将其替换为所需的任何值.
Assume Problem
is a model class, and difficulty
is a virtual attribute. delete Problem.prototype.difficulty
returns false, and the attribute is still there, so I can't replace it with any value I want.
我也尝试过
var p = new Problem();
delete p.difficulty;
p.difficulty = Problem.INT_EASY;
那没有用.
将未定义的值分配给Problem.prototype.difficulty
或使用sinon.stub(Problem.prototype, 'difficulty').returns(Problem.INT_EASY);
将在执行时抛出异常"TypeError:无法读取未定义的属性'scope'"
Assigning undefined to Problem.prototype.difficulty
or using sinon.stub(Problem.prototype, 'difficulty').returns(Problem.INT_EASY);
would throw an exception "TypeError: Cannot read property 'scope' of undefined", while doing
var p = new Problem();
sinon.stub(p, 'difficulty').returns(Problem.INT_EASY);
将引发错误"TypeError:尝试将字符串属性难度包装为函数".
would throw an error "TypeError: Attempted to wrap string property difficulty as function".
我的想法不多了.帮帮我!谢谢!
I am running out of ideas. Help me out! Thanks!
推荐答案
mongoose internally uses Object.defineProperty
for all properties. Since they are defined as non-configurable, you can't delete them, and you can't re-configure them, either.
但是,您可以做的是覆盖模型的get
和set
方法,这些方法用于获取和设置任何属性:
What you can do, though, is overwriting the model’s get
and set
methods, which are used to get and set any property:
var p = new Problem();
p.get = function (path, type) {
if (path === 'difficulty') {
return Problem.INT_EASY;
}
return Problem.prototype.get.apply(this, arguments);
};
或者,一个使用sinon.js的完整示例:
Or, a complete example using sinon.js:
var mongoose = require('mongoose');
var sinon = require('sinon');
var problemSchema = new mongoose.Schema({});
problemSchema.virtual('difficulty').get(function () {
return Problem.INT_HARD;
});
var Problem = mongoose.model('Problem', problemSchema);
Problem.INT_EASY = 1;
Problem.INT_HARD = 2;
var p = new Problem();
console.log(p.difficulty);
sinon.stub(p, 'get').withArgs('difficulty').returns(Problem.INT_EASY);
console.log(p.difficulty);
这篇关于对猫鼬模型的虚拟属性进行存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!