【问题标题】:Mocking mongoose.save() to resolve `this` when calling `this.save()`调用 `this.save()` 时模拟 mongoose.save() 以解决 `this`
【发布时间】:2019-08-05 21:00:39
【问题描述】:

我正在尝试为我们使用猫鼬的应用程序编写单元测试。我在模型上有实例方法,调用 this.save()

例如。

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

有没有办法存根 mongoose save 以返回当前的 this 对象?

基本上是这样的:

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

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

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

【问题讨论】:

    标签: unit-testing testing mongoose mocha.js sinon


    【解决方案1】:

    来自 MDN this doc

    当函数作为对象的方法被调用时,其this 被设置为调用该方法的对象。


    在您的代码示例中,save 始终作为MyModel 对象的方法调用,因此如果您使用callsFake 存根save 并将其传递给function,则其中this 的值function 将是调用 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,上述将不起作用,因为:

    在箭头函数中,this 保留封闭词法上下文的 this 的值。

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

    【讨论】:

    • 为什么不使用sinon.stub(MyModel.prototype, 'save').resolves(this)?只是好奇是否有实施偏好
    • 该死,我对 javascript 世界还比较陌生,没有意识到 this 这样的文字工作。很高兴知道!谢谢
    猜你喜欢
    • 2021-08-15
    • 2014-09-23
    • 2022-01-10
    • 2022-01-18
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多