Jest 24 ๐ Globals Cleanup โ globalsCleanup ‘on’ for memory reduction in v30
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
| Value | Effect | Use When |
|---|---|---|
'on' | Replace the global object at teardown | Default for node and jsdom in Jest 30 |
'off' | Leave the global object in place | A suite depends on a global surviving |
'soft' | Remove framework globals, keep user globals | A setup file assigns a user global |
What the Cleanup Fixes
| Leak | Fixed by 'on' |
|---|---|
| Uncleared timer | Yes |
| Unremoved listener | Yes |
Property assigned to global | Yes |
| Module-level singleton | No |
| Pending promise | No |
The Diagnostics and Hooks
| Knob | Purpose |
|---|---|
globalsCleanup | The config option |
handleGlobalsCleanup() | The environment-level hook |
--detectLeaks | Report a heap growth |
--runInBand | Pair 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Global missing in the next file | Default 'on' replaced the object | Use 'soft' or a setup file |
| Leak still reported | Module-level singleton or pending promise | Fix the source, not the config |
handleGlobalsCleanup not called | Custom environment does not implement it | Implement the hook |
--detectLeaks slows the suite | Heap snapshots per file | Run it as a one-off |
'off' set to silence a failure | The leak is still there | Fix 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
| Item | Value |
|---|---|
| Option | globalsCleanup |
| Default in Jest 30 | 'on' for node and jsdom |
| Full cleanup | 'on' |
| Legacy behavior | 'off' |
| Framework-only cleanup | 'soft' |
| Environment hook | handleGlobalsCleanup() |
| Diagnostic flag | --detectLeaks |
| What it fixes | Timer, listener, global property leaks |
| What it does not fix | Singleton and pending-promise leaks |
| Config location | test.globalsCleanup |
Key takeaways:
globalsCleanup: 'on'is the Jest 30 default for thenodeandjsdomenvironments. At the end of each test file, the environment replaces itsglobalobject 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
globalare 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.--detectLeaksis 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 theglobalsCleanupoption.
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.
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!