| | |

Jest 24 ๐Ÿƒ Globals Cleanup โ€” globalsCleanup ‘on’ for memory reduction in v30

โฑ๏ธ Estimated read: 13 min | |

Jest’s test environment is a sandbox: every test file gets its own global object, its own timers, its own module registry, and its own set of globals injected by the framework and by the environment (jsdom or node). When a test file finishes, Jest tears down the environment, but JavaScript’s garbage collector can only reclaim that memory if nothing still references it. The problem is that test files routinely leave references behind โ€” a leaked timer, an event listener, a closure captured by a global, a promise that resolves after the test ends โ€” and those references keep the entire environment alive past the end of the file. That is the memory leak that the globalsCleanup option in Jest 30 addresses.

This chapter covers the globalsCleanup option introduced in Jest 30: the 'on' value that performs the new teardown, the 'off' value that preserves the legacy behavior, the 'soft' value that cleans only what it safely can, and the --detectLeaks flag that reports a leak rather than fixing it. It also covers the environment-level hook that lets a custom environment opt into the cleanup and the two scenarios where the cleanup does not apply.

Key point: globalsCleanup: 'on' is Jest 30’s new default for the node and jsdom environments, and it replaces the environment’s global object with a fresh one at the end of every test file so that leaked references do not keep the old environment alive; 'off' restores the pre-30 behavior and 'soft' removes only the framework globals and leaves the user’s globals intact.


Why globalsCleanup exists

The leaked-environment problem. A Jest environment is a heavyweight object. The jsdom environment builds a full DOM, and the node environment builds a module registry and a timer table. When a test file leaves a reference to a global, a timer, or a listener, the environment cannot be collected, and the memory of the DOM and the registry stays allocated for the rest of the run. In a large suite the accumulation is what pushes a CI run into an out-of-memory crash.

The timer and listener leaks. The most common leak is a timer that a test starts and never clears. A setInterval that keeps firing holds the callback, the callback’s closure, and everything the closure references. The second most common is an event listener on window or process that the test adds and never removes. Both leaks are invisible while the file runs and both keep the environment alive after it ends.

The global assignment. A test that writes global.myThing = ... or window.myThing = ... and never deletes it leaves the property on the global object. The property is a reference, and the reference keeps the value alive. The old Jest behavior did not remove the property, so the value survived the environment teardown.

The pre-30 workaround. Before Jest 30, the workaround was testEnvironment: "node" with a manual afterEach that reset the globals, or a custom environment whose teardown deleted the known properties. Both workarounds are error-prone because the test author has to enumerate the globals to delete, and a new global added by a dependency is missed.

The trade-off. The cleanup replaces the global object, which means that a value a test stored on global in one file is not visible in the next file. That is the intended behavior โ€” the isolation is the point โ€” but a suite that relied on the leak as a communication channel between files breaks. The 'soft' value exists for that suite: it removes the framework globals and leaves the user’s globals in place.


a. The globalsCleanup option and its three values

The option lives under the test key in the config, and its type is 'on' | 'off' | 'soft'. The default in Jest 30 is 'on' for the node and jsdom environments, and the 'off' value restores the pre-30 behavior for a suite that needs the old semantics.

// jest.config.ts
import type { Config } from "jest";

const config: Config = {
  test: {
    // The default in Jest 30 for node and jsdom
    globalsCleanup: "on", // 'on' | 'off' | 'soft'
  },
};

export default config;

The 'on' value is the full cleanup. At the end of each test file, the environment’s global object is replaced with a fresh one, and the old object is dropped so that the garbage collector can reclaim it along with everything it referenced. The replacement happens in the environment’s teardown, which runs after afterAll and after the last test.

The 'off' value is the legacy behavior. The environment’s global object is left in place, and any leak a test created persists. The value exists for a suite that depends on a global surviving between files, and it is a compatibility escape hatch rather than a recommendation.

The 'soft' value is the middle ground. It removes the globals that Jest and the environment injected โ€” expect, test, describe, the jest object, and the environment’s own globals โ€” and leaves the properties the user’s test code assigned. A suite that sets global.featureFlag = true in a setup file and reads it in a test keeps working under 'soft'.

// The difference in one test file
global.myLeakedValue = { large: "payload" };

test("uses the value", () => {
  expect(global.myLeakedValue).toBeDefined(); // passes in all three modes
});

// After the file:
// 'on'   โ†’ global.myLeakedValue is gone, the old global is collectable
// 'soft' โ†’ global.myLeakedValue is still there, the framework globals are gone
// 'off'  โ†’ global.myLeakedValue is still there, nothing is cleaned

b. The environment-level hook and the detectLeaks flag

A custom environment can opt into the cleanup without the config option. The TestEnvironment interface in Jest 30 adds a handleGlobalsCleanup method, and the environment calls it from its own teardown. The method is what the built-in node and jsdom environments implement, and a third-party environment that does not implement it falls back to the 'off' behavior.

// my-environment.ts
import { TestEnvironment } from "jest-environment-node";

class MyEnvironment extends TestEnvironment {
  async handleGlobalsCleanup(): Promise<void> {
    // The custom environment decides what to remove
    // The default implementation clears the framework globals
    await super.handleGlobalsCleanup();
  }
}

export default MyEnvironment;

The --detectLeaks flag is the diagnostic, not the fix. With the flag on, Jest takes a heap snapshot at the start of the file and another at the end, and it fails the file if the heap grew past a threshold. The flag is expensive and it is a debugging tool rather than a CI default; the globalsCleanup: 'on' option is the fix, and --detectLeaks is what points at the file that needs it.

# Find the file that leaks, then let globalsCleanup fix it
npx jest --detectLeaks --runInBand

# The output names the file whose heap grew
# Fix the leak in that file, or rely on globalsCleanup

The globalsCleanup option does not apply to a custom environment that does not implement handleGlobalsCleanup, and it does not apply to the @jest/environment package’s base class. The two cases are the reason the option is documented as applying to the built-in environments rather than to every environment.


c. The leaks the cleanup fixes and the leaks it does not

The cleanup fixes the reference leaks. A timer that a test leaves running, a listener that a test leaves attached, a property that a test assigns to global โ€” all three are references from the old global object, and replacing the object drops them. The garbage collector reclaims the timer callback, the listener, and the assigned value along with the environment.

// A leak that globalsCleanup: 'on' fixes
test("starts an interval and forgets it", () => {
  setInterval(() => {
    // the callback closes over a large object
    consume(largeObject);
  }, 1000);
  // no clearInterval โ€” the timer keeps the closure alive
});

// Under 'on', the environment's teardown replaces the global,
// the timer is no longer referenced, and the GC reclaims it

The cleanup does not fix a leak that lives outside the global object. A module-level variable in a source file, a singleton that holds a reference, a database connection pool โ€” those are not properties of global, and replacing the global does not touch them. The --detectLeaks flag reports the growth, and the fix for those leaks is in the source code rather than in the Jest config.

// A leak that globalsCleanup: 'on' does NOT fix
// module-level singleton in src/cache.ts
const cache = new Map<string, Buffer>();

export function remember(key: string, value: Buffer): void {
  cache.set(key, value); // grows forever, not a global property
}

// The fix is a bounded cache or a clear() in afterAll,
// not the globalsCleanup option

The cleanup also does not fix a pending promise. A test that starts an async operation and does not await it leaves a pending promise whose then callbacks reference the test’s closure. The promise is not a global property, and the replacement does not cancel it. The globalsCleanup option reduces the memory that a leaked environment holds; it does not make an async test correct.


Complete Example Session

// ============================================
// PART 1: THE CONFIG WITH THE DEFAULT
// ============================================
// jest.config.ts
import type { Config } from "jest";

const config: Config = {
  test: {
    globalsCleanup: "on", // the Jest 30 default for node and jsdom
  },
};

export default config;

// ============================================
// PART 2: THE LEGACY MODE
// ============================================
// jest.config.ts
const legacyConfig: Config = {
  test: {
    globalsCleanup: "off", // pre-30 behavior, leaks persist
  },
};

// ============================================
// PART 3: THE SOFT MODE
// ============================================
// jest.config.ts
const softConfig: Config = {
  test: {
    globalsCleanup: "soft", // framework globals removed, user globals kept
  },
};

// ============================================
// PART 4: A LEAK THE CLEANUP FIXES
// ============================================
test("leaks an interval", () => {
  setInterval(() => consume(largeObject), 1000);
  // no clearInterval โ€” 'on' drops the reference at teardown
});

// ============================================
// PART 5: A LEAK THE CLEANUP DOES NOT FIX
// ============================================
// src/cache.ts โ€” a module-level singleton, not a global
const cache = new Map<string, Buffer>();
export function remember(key: string, value: Buffer): void {
  cache.set(key, value); // the fix is a bounded cache, not globalsCleanup
}

// ============================================
// PART 6: THE CUSTOM ENVIRONMENT HOOK
// ============================================
import { TestEnvironment } from "jest-environment-node";

class MyEnvironment extends TestEnvironment {
  async handleGlobalsCleanup(): Promise<void> {
    await super.handleGlobalsCleanup(); // the environment opts in
  }
}

// ============================================
// PART 7: THE DIAGNOSTIC FLAG
// ============================================
// package.json
// "scripts": { "test:leaks": "jest --detectLeaks --runInBand" }

// ============================================
// PART 8: THE USER GLOBAL UNDER soft
// ============================================
global.featureFlag = true;

test("reads the user global", () => {
  expect(global.featureFlag).toBe(true); // survives under 'soft'
});

// ============================================
// PART 9: THE USER GLOBAL UNDER on
// ============================================
test("the user global is gone in the next file", () => {
  // Under 'on', the next file's global is a fresh object
  expect((global as { featureFlag?: boolean }).featureFlag).toBeUndefined();
});

// ============================================
// PART 10: THE PENDING PROMISE
// ============================================
test("starts but does not await", () => {
  fetchData().then((value) => consume(value));
  // the promise is not a global property; 'on' does not cancel it
});

The parts covered the three option values, a leak the cleanup fixes, a leak it does not fix, the environment-level hook, the --detectLeaks diagnostic, the soft mode’s user-global behavior, and the pending promise that the cleanup does not address.


Quick Reference

The Option Values

ValueEffectUse When
'on'Replace the global object at teardownDefault for node and jsdom in Jest 30
'off'Leave the global object in placeA suite depends on a global surviving
'soft'Remove framework globals, keep user globalsA setup file assigns a user global

What the Cleanup Fixes

LeakFixed by 'on'
Uncleared timerYes
Unremoved listenerYes
Property assigned to globalYes
Module-level singletonNo
Pending promiseNo

The Diagnostics and Hooks

KnobPurpose
globalsCleanupThe config option
handleGlobalsCleanup()The environment-level hook
--detectLeaksReport a heap growth
--runInBandPair with --detectLeaks for a readable report

Best Practices

โœ… Do This:

// Keep the Jest 30 default
globalsCleanup: "on"                                         // โœ…

// Use soft when a setup file assigns a user global
globalsCleanup: "soft"                                       // โœ…

// Clear the timers you start
const id = setInterval(fn, 1000); afterEach(() => clearInterval(id)); // โœ…

// Use --detectLeaks as a one-off diagnostic
npx jest --detectLeaks --runInBand                           // โœ…

// Implement the hook in a custom environment
async handleGlobalsCleanup() { await super.handleGlobalsCleanup(); } // โœ…

โŒ Don’t Do This:

// Set 'off' to silence a leak
globalsCleanup: "off" // the leak is still there                  // โŒ

// Rely on a global surviving between files
global.shared = value; // breaks under the default 'on'          // โŒ

// Blame globalsCleanup for a module-level singleton leak
const cache = new Map(); // the fix is a bounded cache           // โŒ

// Run --detectLeaks in CI by default
// it is expensive and it is a debugging tool                    // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Global missing in the next fileDefault 'on' replaced the objectUse 'soft' or a setup file
Leak still reportedModule-level singleton or pending promiseFix the source, not the config
handleGlobalsCleanup not calledCustom environment does not implement itImplement the hook
--detectLeaks slows the suiteHeap snapshots per fileRun it as a one-off
'off' set to silence a failureThe leak is still thereFix the timer or listener

Real-World Examples

1. The default config

test: { globalsCleanup: "on" }

2. The legacy escape hatch

test: { globalsCleanup: "off" }

3. The soft mode

test: { globalsCleanup: "soft" }

4. The custom environment hook

async handleGlobalsCleanup(): Promise<void> { await super.handleGlobalsCleanup(); }

5. The diagnostic flag

npx jest --detectLeaks --runInBand

6. A timer leak the cleanup fixes

setInterval(() => consume(largeObject), 1000); // no clearInterval

7. A singleton leak the cleanup does not fix

const cache = new Map<string, Buffer>(); // module-level, not a global

8. A user global under soft

global.featureFlag = true; // survives under 'soft'

9. A pending promise the cleanup does not fix

fetchData().then((value) => consume(value)); // not awaited

10. The environment class

class MyEnvironment extends TestEnvironment { /* ... */ }

Visual

The Three Modes at Teardown

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  'on'                                                    โ”‚
โ”‚  global object โ”€โ”€โ–บ replaced with a fresh object          โ”‚
โ”‚  old object โ”€โ”€โ”€โ”€โ–บ dropped, GC reclaims it                โ”‚
โ”‚                                                          โ”‚
โ”‚  'soft'                                                  โ”‚
โ”‚  framework globals โ”€โ”€โ–บ removed                           โ”‚
โ”‚  user globals โ”€โ”€โ”€โ”€โ”€โ”€โ–บ kept                               โ”‚
โ”‚                                                          โ”‚
โ”‚  'off'                                                   โ”‚
โ”‚  global object โ”€โ”€โ–บ left in place, leaks persist          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

What the Cleanup Fixes

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  LEAK                            FIXED BY 'on'           โ”‚
โ”‚  uncleared setInterval           yes                     โ”‚
โ”‚  unremoved event listener        yes                     โ”‚
โ”‚  property on global              yes                     โ”‚
โ”‚                                                          โ”‚
โ”‚  module-level singleton          no                      โ”‚
โ”‚  pending promise                 no                      โ”‚
โ”‚                                                          โ”‚
โ”‚  Why: the cleanup replaces the global object, and        โ”‚
โ”‚  only the first three are references from that object    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Diagnostic Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  CI run runs out of memory                               โ”‚
โ”‚         โ”‚                                                โ”‚
โ”‚         โ–ผ                                                โ”‚
โ”‚  npx jest --detectLeaks --runInBand                      โ”‚
โ”‚         โ”‚                                                โ”‚
โ”‚         โ–ผ                                                โ”‚
โ”‚  the output names the file whose heap grew               โ”‚
โ”‚         โ”‚                                                โ”‚
โ”‚         โ–ผ                                                โ”‚
โ”‚  fix the timer or listener in that file                  โ”‚
โ”‚  or rely on globalsCleanup: 'on' for the environment     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Environment Hook

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  TestEnvironment                                         โ”‚
โ”‚    โ”œโ”€โ”€ setup()                                           โ”‚
โ”‚    โ”œโ”€โ”€ runScript()                                       โ”‚
โ”‚    โ”œโ”€โ”€ teardown()                                        โ”‚
โ”‚    โ”‚     โ””โ”€โ”€ handleGlobalsCleanup()                      โ”‚
โ”‚    โ”‚           โ””โ”€โ”€ replaces global when 'on'             โ”‚
โ”‚    โ””โ”€โ”€ handleGlobalsCleanup()                            โ”‚
โ”‚          โ”œโ”€โ”€ built-in node and jsdom implement it        โ”‚
โ”‚          โ””โ”€โ”€ a custom environment opts in by overriding  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
OptionglobalsCleanup
Default in Jest 30'on' for node and jsdom
Full cleanup'on'
Legacy behavior'off'
Framework-only cleanup'soft'
Environment hookhandleGlobalsCleanup()
Diagnostic flag--detectLeaks
What it fixesTimer, listener, global property leaks
What it does not fixSingleton and pending-promise leaks
Config locationtest.globalsCleanup

Key takeaways:

  • globalsCleanup: 'on' is the Jest 30 default for the node and jsdom environments. At the end of each test file, the environment replaces its global object with a fresh one, and the old object becomes collectable along with everything it referenced.
  • The cleanup fixes reference leaks from the global object. An uncleared timer, an unremoved listener, and a property assigned to global are all references from the old object, and replacing it drops them.
  • The cleanup does not fix a module-level singleton or a pending promise. Those are not global properties, and the fix is in the source code rather than in the Jest config.
  • 'soft' is for the suite that assigns a user global. It removes the framework globals and keeps the user’s properties, and it is the middle ground between the full cleanup and the legacy behavior.
  • --detectLeaks is the diagnostic, not the fix. The flag reports the file whose heap grew, and the fix is the timer or listener in that file or the globalsCleanup option.

Remember: The Jest environment is a sandbox, and the sandbox is only reclaimed when nothing references it. The globalsCleanup: 'on' option replaces the global object at the end of every test file so that the leaked timers, listeners, and global properties no longer keep the environment alive. Use 'soft' when a setup file assigns a user global, keep 'off' only as a legacy escape hatch, and reach for --detectLeaks when the question is which file leaks rather than whether to clean up.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!