简体   繁体   中英

How to mock a deeply nested function with TypeScript and Jest

I want to test my modules and mock axios external dependencies. The problem is that the methods I directly test do not (directly) import 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.

Since B is a very thin layer around axios, I do not want to test it directly. I would rather just test A, and have axios being mocked.

How to do this? If instead of axios, I have a custom module C, does it make any difference?

Yes you can mock a module - see 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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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