From 74233142b20c7d9dbc8b8bde8f964b0850b249b3 Mon Sep 17 00:00:00 2001 From: Eyal Roth Date: Sat, 27 Jul 2024 19:31:32 +0300 Subject: [PATCH] #15215 Reduce memory leak in node env by fully uninstalling source-map-support --- packages/jest-environment-node/src/index.ts | 3 +++ packages/jest-runner/src/runTest.ts | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) 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 {