我正在尝试为使用猫鼬的应用程序编写单元测试。我在模型上有调用this.save()
的实例方法
例如。
MyModel.methods.update = function(data) {
this.param = data
this.save().then(updatedModel => {
return updatedModel
})
}
有没有办法存根猫鼬保存以返回当前this
对象?
本质上,像这样:
const save = sinon.stub(MyModel.prototype, 'save').resolves(this);
但这是实例方法中对此的引用。
希望我描述的内容有意义。任何帮助,不胜感激。 谢谢!
来自 MDNthis
文档:
当函数作为对象的方法调用时,其
this
设置为调用该方法的对象。
在代码示例中,save
始终作为MyModel
对象的方法调用,因此,如果使用callsFake
存根save
并向其传递function
,则该function
中的this
值将是调用save
MyModel
对象:
// 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); });
请注意,如果您使用箭头函数,上述内容将不起作用,因为:
在箭头函数中,
this
保留封闭词法上下文this
的值。
// Returns a Promise that resolves to whatever 'this' is right now
sinon.stub(MyModel.prototype, 'save').callsFake(() => Promise.resolve(this));