From 9ff3d3e5da643b5acee21ccc373261354556a305 Mon Sep 17 00:00:00 2001 From: Eyal Roth Date: Sat, 27 Jul 2024 19:31:00 +0300 Subject: [PATCH] #15215 Reduce memory leak in node env by clearing event listeners in teardown --- packages/jest-environment-node/src/index.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/jest-environment-node/src/index.ts b/packages/jest-environment-node/src/index.ts index a6a0afa6dccb..93429afaead4 100644 --- a/packages/jest-environment-node/src/index.ts +++ b/packages/jest-environment-node/src/index.ts @@ -214,7 +214,23 @@ export default class NodeEnvironment implements JestEnvironment { if (this.fakeTimersModern) { this.fakeTimersModern.dispose(); } - this.context = null; + + if (this.context) { + // remove any leftover listeners that may hold references to sizable memory + this.context.process.removeAllListeners(); + const cluster = runInContext( + "require('node:cluster')", + Object.assign(this.context, { + require: + // get native require instead of webpack's + // @ts-expect-error https://webpack.js.org/api/module-variables/#__non_webpack_require__-webpack-specific + __non_webpack_require__, + }), + ); + cluster.removeAllListeners(); + + this.context = null; + } this.fakeTimers = null; this.fakeTimersModern = null; this._globalProxy.clear();