Jest has clearly addressed how to mock a module in this link https://jestjs.io/docs/en/manual-mocks#mocking-node-modules.
It has an important note as following:
Note: In order to mock properly, Jest needs jest.mock(‘moduleName’) to be in the same scope as the require/import statement.
On the other hand, Most of use cases jest.mock
is supposed to be called at the top level of module should work properly:
const axios = require('axios');
// At the same scope with `require`
jest.mock('axios');