如何重构调用函数的函数,以便可以使用类型脚本和sinon对其进行测试? [英] How to refactor a function that calls a function so that it can be tested using typescript and sinon?
本文介绍了如何重构调用函数的函数,以便可以使用类型脚本和sinon对其进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码
import {
getIndexDocument
} from "@assets";
class MetaController {
public async exploreIndexDocument(): Promise<Asset | undefined> {
const {
result: { assignedDirectories }
} = await getIndexDocument(this._serviceConfig).catch(err => {
throw new Error(`[AssetsController] Bad response on discovering index doc because ${err}`);
});
}
}
如您所见,explreIndexDocument正在调用函数getIndexDocument。我想编写一个ExplreIndexDocument测试,但我不能使用SINON来存根getIndexDocument,因为SINON不允许您存根函数。我如何构建此类以执行此操作?
推荐答案
您需要某种注入存根的方法,以便您的类实例调用存根而不是外部库。This answer阐述了一些替代方案。注入存根的替代方法是替换要导入的整个模块。这是使用链接seam调用的。This answer shows one way,并列出了可帮助您执行此操作的各种模块加载器。
就我个人而言,我已经慢慢摆脱了模块模拟技术,并试图让自己保持在依赖注入的世界中(备选方案1),因为无论底层环境如何,这种方法都可以工作,并且任何初级程序员都可以阅读测试。最小侵入性的方法可以简单地如下所示:
import {
getIndexDocument
} from "@assets";
class MetaController {
private getIndexDocument: (config:object) => Promise<{assignedDirectories:any> };
constructor(deps = {getIndexDocument}) {
this.getIndexDocument = getIndexDocument;
}
public async exploreIndexDocument(): Promise<Asset | undefined> {
const {
result: { assignedDirectories }
} = await this.getIndexDocument(this._serviceConfig).catch(err => {
throw new Error(`[AssetsController] Bad response on discovering index doc because ${err}`);
});
}
}
您现在可以非常轻松地测试:
const fake = sinon.fake.resolves({ assignedDirectories: ['/foo/dir'] });
const controller = new MetaController({getIndexDocument: fake});
const promise = controller.exploreIndexDocument();
expect(fake.calledOnce).toBe(true);
// further assertions follow ... see https://sinonjs.org/releases/latest/fakes/
这篇关于如何重构调用函数的函数,以便可以使用类型脚本和sinon对其进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文