Skip to content

Commit

Permalink
jestjs#15215 Reduce memory leak in node env by fully uninstalling sou…
Browse files Browse the repository at this point in the history
…rce-map-support
  • Loading branch information
eyalroth committed Aug 2, 2024
1 parent b113b44 commit fb7358c
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions packages/jest-runner/src/runTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -377,8 +390,6 @@ async function runTestInternal(
});
} finally {
await tearDownEnv();

sourcemapSupport.resetRetrieveHandlers();
}
}

Expand Down

0 comments on commit fb7358c

Please sign in to comment.