Skip to content

Commit 338243a

Browse files
committed
#15215 Reduce memory leak in node env by fully uninstalling source-map-support
1 parent 213c3b2 commit 338243a

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090

9191
- `[*]` [**BREAKING**] Bundle all of Jest's modules into `index.js` ([#12348](https://github.com/jestjs/jest/pull/12348), [#14550](https://github.com/jestjs/jest/pull/14550) & [#14661](https://github.com/jestjs/jest/pull/14661))
9292
- `[jest-haste-map]` Only spawn one process to check for `watchman` installation ([#14826](https://github.com/jestjs/jest/pull/14826))
93+
- `[jest-runner]` Better cleanup `source-map-support` after test to resolve (minor) memory leak ([#15233](https://github.com/jestjs/jest/pull/15233))
9394

9495
### Chore & Maintenance
9596

packages/jest-runner/src/runTest.ts

+15-4
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' && e !== null && '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)