【问题标题】:Sinon stub mongoose save to resolve the object which called saveSinon stub mongoose save 来解析调用 save 的对象
【发布时间】:2019-09-26 19:53:03
【问题描述】:
我有以下代码:
const newImage = new Image(...);
newImage.save().then(image => {...})
有没有办法存根 Image 的 save 方法来解析调用它的对象? IE。我希望then 子句中的image 与newImage 相同
类似的东西
sinon.stub(Image.prototype, 'save').resolves(theCallingObject);
这可能吗?任何帮助表示赞赏。
谢谢!
【问题讨论】:
标签:
node.js
testing
mongoose
mocha.js
sinon
【解决方案1】:
你可以使用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!
})