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

问题描述 投票:0回答:1

我正在尝试为我们使用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);

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

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

unit-testing testing mongoose mocha sinon
1个回答
1
投票

来自MDN this doc

当一个函数被调用为一个对象的方法时,它的this被设置为调用该方法的对象。


在你的代码示例中,save总是被称为MyModel对象的方法,所以如果你通过使用save来传递callsFake并传递function,那个thisfunction的值将是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));
© www.soinside.com 2019 - 2024. All rights reserved.