【发布时间】:2017-06-08 02:36:16
【问题描述】:
晚上好!
我正试图让我的头脑在一般的嘲笑中,这似乎是一个很好的例子。
我有一个类,它处理图像加载并使用别名(例如,this._imgLoaded[path] = image)跟踪所述图像
export default class Loader {
// Constructor and what not
_loadImage(path) {
return new Promise((resolve, reject) => {
let image = new Image();
image.src = path;
image.onload = () => resolve(image);
image.onerror = () =>
reject(new Error("Image is not defined. Unable to load it."));
});
}
async loadImage(path, alias) {
const newPath = this._enrichRelativePath(path);
let image;
try {
image = await this._loadImage(newPath);
} catch (error) {
// log and rethrow
console.error(error);
throw error;
}
// cache the loaded image:
this._imgLoaded[newPath] = image;
if (alias) {
this._imgAlias[alias] = newPath;
}
}
}
我认为为了对此进行单元测试,我必须为_loadImage 创建一个模拟函数并让它返回一些东西。
在保持其他功能不变的同时,最好的方法是什么?
附带说明,我使用的是 ES6。
谢谢!
【问题讨论】:
标签: javascript unit-testing mocking jestjs