diff --git a/packages/jest-environment-node/src/index.ts b/packages/jest-environment-node/src/index.ts index 93429afaead4..c404861555c2 100644 --- a/packages/jest-environment-node/src/index.ts +++ b/packages/jest-environment-node/src/index.ts @@ -216,6 +216,9 @@ export default class NodeEnvironment implements JestEnvironment { } if (this.context) { + // source-map-support keeps memory leftovers in `Error.prepareStackTrace` + runInContext("Error.prepareStackTrace = () => '';", this.context); + // remove any leftover listeners that may hold references to sizable memory this.context.process.removeAllListeners(); const cluster = runInContext( diff --git a/packages/jest-runner/src/runTest.ts b/packages/jest-runner/src/runTest.ts index 3bac869fa096..3adab934710c 100644 --- a/packages/jest-runner/src/runTest.ts +++ b/packages/jest-runner/src/runTest.ts @@ -312,8 +312,12 @@ async function runTestInternal( sendMessageToJest, ); } catch (error: any) { - // Access stack before uninstalling sourcemaps - error.stack; + // Access all stacks before uninstalling sourcemaps + let e = error; + while (typeof e === 'object' && 'stack' in e) { + e.stack; + e = e?.cause ?? {}; + } throw error; } finally {