如何重构调用函数的函数,以便可以使用类型脚本和sinon对其进行测试?

编程入门 行业动态 更新时间:2024-10-26 12:29:45
本文介绍了如何重构调用函数的函数,以便可以使用类型脚本和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 sinonjs/releases/latest/fakes/

更多推荐

如何重构调用函数的函数,以便可以使用类型脚本和sinon对其进行测试?

本文发布于:2023-06-07 21:54:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568454.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   对其   可以使用   脚本   进行测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!