我有以下代码:
const newImage = new Image(...);
newImage.save().then(image => {...})
有没有办法 stub Image 的保存方法来解析调用它的对象? IE。我希望 then
子句中的 image
与 newImage
有点像
sinon.stub(Image.prototype, 'save').resolves(theCallingObject);
这可能吗?任何帮助表示赞赏。 谢谢!
最佳答案
您可以使用callsFake
来模拟原型(prototype)方法...
...如果你传递给它一个普通函数(不是箭头函数)那么 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!
})
关于node.js - Sinon stub Mongoose 保存以解析调用保存的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56051603/