I would suggest considering that the mock be setup so that it continues to call the original until the mocks are explicitly reset and setup with the desired mock behaviour just before the test that is interested in the function being mocked.
jest.mock("fs", () => { const originalFs = jest.requireActual("fs"); return { __esModule: true, ...originalFs, // call original by default until specific tests as this avoids breaking // any imports that might perform a readFileSync when loading. readFileSync: jest.fn().mockImplementation((args) => originalFs.readFileSync(args)), }; });
To expand on why, most of the answers will work in most situations, however for any module from the core or an external library that is used by multiple other imports they can create a side effect.
When you use jest.mock("<name>"), it applies before imports are actually executed. Looking at https://jestjs.io/docs/mock-functions#mocking-modules you can see the mock is after the import, but it still works as expected. However in https://jestjs.io/docs/bypassing-module-mocks the mock is created before which may not be obvious that it doesn't matter, even if afterwards jest hooks in early enough to apply the mock before what is in the import is processed.
This means that anything that is imported and tries to create a concrete instance of an object to set as a module property, will get the mocked instance rather than the original.
In some cases this might be what is intended, but more likely this will be surprising. By having the mock pass through to the original call initially, it allows for the function to used by other imports initial setup and can then be switched to use the needed mock implementation before testimg the function that calls it as well.
Obviously if you are mocking something you've written this is less important, more for when working with libraries and frameworks that can have dependencies and behaviour you might not be fully aware of.
In my case I got bitten by the context object in GitHub's @actions/toolkit looking to read a JSON file on load which only caused issues when the GITHUB_EVENT_PATH env var was set. https://github.com/actions/toolkit/blob/main/packages/github/src/context.ts
jest.mock()actually gets hoisted like variables. As a result, they're called before the imports.