我正在尝试为我们使用mongoose的应用程序编写单元测试。我在调用this.save()
的模型上有实例方法
例如。
MyModel.methods.update = function(data) {
this.param = data
this.save().then(updatedModel => {
return updatedModel
})
}
有没有办法存根mongoose保存以返回当前的this
对象?
基本上,这样的事情:
const save = sinon.stub(MyModel.prototype, 'save').resolves(this);
但这是在实例方法中引用它。
希望我所描述的是有道理的。任何帮助表示赞赏。谢谢!
来自MDN this
doc:
当一个函数被调用为一个对象的方法时,它的
this
被设置为调用该方法的对象。
在你的代码示例中,save
总是被称为MyModel
对象的方法,所以如果你通过使用save
来传递callsFake
并传递function
,那个this
中function
的值将是MyModel
被调用的save
对象:
// Returns a Promise that resolves to the MyModel object that save was called on
sinon.stub(MyModel.prototype, 'save').callsFake(function() { return Promise.resolve(this); });
请注意,如果您使用arrow function,则上述操作无效:
在箭头函数中,
this
保留了封闭词汇上下文的this
的值。
// Returns a Promise that resolves to whatever 'this' is right now
sinon.stub(MyModel.prototype, 'save').callsFake(() => Promise.resolve(this));