node.js - Sinon stub mongoose save 来解析调用 save 的对象
问题描述
我有以下代码:
const newImage = new Image(...);
newImage.save().then(image => {...})
有没有办法存根 Image 的保存方法来解析调用它的对象?IE。我希望image
在then
子句中与newImage
就像是
sinon.stub(Image.prototype, 'save').resolves(theCallingObject);
这可能吗?任何帮助表示赞赏。谢谢!
解决方案
您可以使用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!
})
推荐阅读
- scala - Scala - 无法解析符号 flatMap
- javascript - 如何在 React 中获取元素 onClick 的值并将其用作条件
- sharepoint - 断言失败:闯入调试器
- java - 如何导航到对话框,并在等待对话框结果时阻止代码执行?
- python - 如何在使用 ImageDataGenerator 时随机分割图像数据集
- r - 在同一变量的 mutate 中简化多个 if else
- android - 有没有办法告诉 gradle 总是使用 aapt2 的自定义二进制文件?
- python - HuggingFace Tokenizer:如何获取 unicodes 字符串的令牌?
- google-bigquery - 是否可以在 array_agg(BigQuery 中的结构表达式中使用星型表达式?
- scala - 找到 Scala 3 宏:(x$1 : x$1².reflect.Symbol) 必需:quoted.Quotes