嘲笑mongoose.save()在调用"this.save()"时解决"this&quo



我正在尝试为使用猫鼬的应用程序编写单元测试。我在模型上有调用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值将是调用saveMyModel对象:

// 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));

相关内容

最新更新