From fb7358c0e089ccce54e355c4bc0a7fa32e03c09e Mon Sep 17 00:00:00 2001 From: Eyal Roth Date: Fri, 2 Aug 2024 14:43:34 +0300 Subject: [PATCH] #15215 Reduce memory leak in node env by fully uninstalling source-map-support --- packages/jest-runner/src/runTest.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/jest-runner/src/runTest.ts b/packages/jest-runner/src/runTest.ts index ed9a5ed951bd..14e48dc26a91 100644 --- a/packages/jest-runner/src/runTest.ts +++ b/packages/jest-runner/src/runTest.ts @@ -6,6 +6,7 @@ * */ +import {runInContext} from 'node:vm'; import chalk = require('chalk'); import * as fs from 'graceful-fs'; import sourcemapSupport = require('source-map-support'); @@ -208,6 +209,14 @@ async function runTestInternal( const tearDownEnv = async () => { if (!isTornDown) { runtime.teardown(); + + // source-map-support keeps memory leftovers in `Error.prepareStackTrace` + runInContext( + "Error.prepareStackTrace = () => '';", + environment.getVmContext()!, + ); + sourcemapSupport.resetRetrieveHandlers(); + await environment.teardown(); isTornDown = true; } @@ -312,8 +321,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 { @@ -377,8 +390,6 @@ async function runTestInternal( }); } finally { await tearDownEnv(); - - sourcemapSupport.resetRetrieveHandlers(); } }