简体   繁体   English

如何使用 TypeScript 和 Jest 模拟深度嵌套的 function

[英]How to mock a deeply nested function with TypeScript and Jest

I want to test my modules and mock axios external dependencies.我想测试我的模块并模拟 axios 外部依赖项。 The problem is that the methods I directly test do not (directly) import axios.问题是我直接测试的方法没有(直接)导入axios。 It it rather "hidden" behind an intermediate call.它相当“隐藏”在中间调用后面。

Like this, A and B are my custom modules: A calls B, B uses axios So, A does not import axios, only B.像这样,A和B是我的自定义模块:A调用B,B使用axios所以,A不导入axios,只有B。

Since B is a very thin layer around axios, I do not want to test it directly.由于B是axios周围很薄的一层,我不想直接测试。 I would rather just test A, and have axios being mocked.我宁愿只测试 A,并让 axios 被嘲笑。

How to do this?这个怎么做? If instead of axios, I have a custom module C, does it make any difference?如果不是 axios,我有一个自定义模块 C,它有什么区别吗?

Yes you can mock a module - see https://jestjs.io/docs/en/manual-mocks .是的,您可以模拟一个模块 - 请参阅https://jestjs.io/docs/en/manual-mocks To mock axios, just use jest.mock('axios') , then anything imported from 'axios' will be a mock (and you can configure it by standard Jest mock API).要模拟 axios,只需使用jest.mock('axios') ,然后从 'axios' 导入的任何内容都将是一个模拟(您可以通过标准的 Jest 模拟 API 配置它)。 Just note that it will be mocked for the whole test case, so eg if you test a module that uses two other modules each using axios, you can't mock axios for only one of them.请注意,它将针对整个测试用例进行模拟,因此,例如,如果您测试一个模块,该模块使用两个其他模块,每个模块都使用 axios,则不能仅针对其中一个模拟 axios。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM