Skip to content

Instantly share code, notes, and snippets.

@LayZeeDK
Created August 21, 2025 13:23
Show Gist options
  • Save LayZeeDK/d4f2a5b3734ba3c1928133b46514a33e to your computer and use it in GitHub Desktop.
Save LayZeeDK/d4f2a5b3734ba3c1928133b46514a33e to your computer and use it in GitHub Desktop.
Resolve "TypeError: Cannot redefine property: <spyOnMethodName>" in Jest
/// <reference types="jest" />
/**
* Mock ESModule with `default` export to support {@link jest.spyOn}.
*
* Resolve "TypeError: Cannot redefine property: <spyOnMethodName>".
*
* @remarks Should be called before other import statements.
* @see https://jestjs.io/docs/29.7/jest-object#jestmockmodulename-factory-options
*/
export function mockModuleWithDefaultExport(moduleName: string) {
jest.mock(moduleName, () => {
return {
__esModule: true,
...jest.requireActual(moduleName),
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment