首页 > 解决方案 > Sinon stub mongoose save 来解析调用 save 的对象

问题描述

我有以下代码:

const newImage = new Image(...);
newImage.save().then(image => {...})

有没有办法存根 Image 的保存方法来解析调用它的对象?IE。我希望imagethen子句中与newImage

就像是 sinon.stub(Image.prototype, 'save').resolves(theCallingObject);

这可能吗?任何帮助表示赞赏。谢谢!

标签: node.jstestingmongoosemocha.jssinon

解决方案


您可以使用callsFake模拟原型方法...

...如果您将其传递给普通函数(而不是箭头函数),那么this它将是模拟函数中的实例:

const sinon = require('sinon');
const assert = require('assert');

class Image {
  async save() {
    return 'something else';
  }
}

it('should work', async function() {
  sinon.stub(Image.prototype, 'save').callsFake(
    function() {  // <= normal function
      return Promise.resolve(this);  // <= this is the instance
    }
  );
  const newImage = new Image();
  const result = await newImage.save();
  assert.strictEqual(result, newImage);  // Success!
})

推荐阅读