Skip to content

Commit fb7358c

Browse files
committed
jestjs#15215 Reduce memory leak in node env by fully uninstalling source-map-support
1 parent b113b44 commit fb7358c

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

packages/jest-runner/src/runTest.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*
77
*/
88

9+
import {runInContext} from 'node:vm';
910
import chalk = require('chalk');
1011
import * as fs from 'graceful-fs';
1112
import sourcemapSupport = require('source-map-support');
@@ -208,6 +209,14 @@ async function runTestInternal(
208209
const tearDownEnv = async () => {
209210
if (!isTornDown) {
210211
runtime.teardown();
212+
213+
// source-map-support keeps memory leftovers in `Error.prepareStackTrace`
214+
runInContext(
215+
"Error.prepareStackTrace = () => '';",
216+
environment.getVmContext()!,
217+
);
218+
sourcemapSupport.resetRetrieveHandlers();
219+
211220
await environment.teardown();
212221
isTornDown = true;
213222
}
@@ -312,8 +321,12 @@ async function runTestInternal(
312321
sendMessageToJest,
313322
);
314323
} catch (error: any) {
315-
// Access stack before uninstalling sourcemaps
316-
error.stack;
324+
// Access all stacks before uninstalling sourcemaps
325+
let e = error;
326+
while (typeof e === 'object' && 'stack' in e) {
327+
e.stack;
328+
e = e?.cause ?? {};
329+
}
317330

318331
throw error;
319332
} finally {
@@ -377,8 +390,6 @@ async function runTestInternal(
377390
});
378391
} finally {
379392
await tearDownEnv();
380-
381-
sourcemapSupport.resetRetrieveHandlers();
382393
}
383394
}
384395

0 commit comments

Comments
 (0)