Denis Obydennykhon Stack Overflow • Recommends
On “What is happening under the hood that allows jest to mock a function that is called from outside the test file?”
Jest utilizes nodejs vm functionality, that allows to control and modify code execution
https://nodejs.org/api/vm.html
That is done in jest-runtime package
https://github.com/facebook/jest/blob/46c9c13811ca20a887e2826c03852f2ccdebda7a/packages/jest-runtime/src/index.ts#L531
You can see detailed description in this video describing jest architecture
jest-runtime && node vm
link to this video
require interception
link to this video