在调用 `this.save()` 时模拟 mongoose.save() 来解析 `this`

Mocking mongoose.save() to resolve `this` when calling `this.save()`

我正在尝试为我们使用猫鼬的应用程序编写单元测试。我在调用 this.save()

的模型上有实例方法

例如

MyModel.methods.update = function(data) {
    this.param = data
    this.save().then(updatedModel => {
        return updatedModel
    })
}

有没有办法将 mongoose 保存到 return 当前 this 对象?

基本上是这样的:

const save = sinon.stub(MyModel.prototype, 'save').resolves(this);

但这是在实例方法中引用this。

希望我描述的是有道理的。任何帮助表示赞赏。 谢谢!

来自 MDN this doc:

When a function is called as a method of an object, its this is set to the object the method is called on.


在您的代码示例中,save 始终作为 MyModel 对象的方法调用,因此如果您使用 callsFake 存根 save 并将其传递给 functionfunctionthis 的值将是调用 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); });

请注意,如果您使用 arrow function,上述 将不会 工作,因为:

In arrow functions, this retains the value of the enclosing lexical context's this.

// Returns a Promise that resolves to whatever 'this' is right now
sinon.stub(MyModel.prototype, 'save').callsFake(() => Promise.resolve(this));