or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-jest-leak-detector

Module for verifying whether an object has been garbage collected or not

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jest-leak-detector@30.1.x

To install, run

npx @tessl/cli install tessl/npm-jest-leak-detector@30.1.0

index.mddocs/

Jest Leak Detector

Jest Leak Detector is a TypeScript utility for verifying whether an object has been garbage collected or not. It creates weak references to objects and forces garbage collection to determine if objects are properly released from memory. This library is primarily used within the Jest testing framework ecosystem for memory leak detection during test execution.

Package Information

  • Package Name: jest-leak-detector
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install jest-leak-detector

Core Imports

import LeakDetector from "jest-leak-detector";

For CommonJS:

const LeakDetector = require("jest-leak-detector");

Basic Usage

import LeakDetector from "jest-leak-detector";

async function detectLeak() {
  let reference = { data: "some object" };
  
  // Create detector to monitor the object
  const detector = new LeakDetector(reference);
  
  // Check if object is still in memory (should be true)
  let isLeaking = await detector.isLeaking();
  console.log(isLeaking); // true
  
  // Remove reference
  reference = null;
  
  // Check again after nullifying reference (should be false)
  isLeaking = await detector.isLeaking();
  console.log(isLeaking); // false
}

Capabilities

Leak Detection

Creates a leak detector that monitors whether a given object has been garbage collected.

class LeakDetector {
  /**
   * Creates a leak detector for monitoring object garbage collection
   * @param value - The object to monitor (cannot be a primitive value)
   * @param opt - Optional configuration for detection behavior
   * @throws TypeError if value is a primitive (undefined, null, boolean, number, string, symbol)
   */
  constructor(value: unknown, opt?: LeakDetectorOptions);

  /**
   * Checks if the monitored object is still in memory
   * Forces garbage collection and checks if the object is still referenced
   * @returns Promise resolving to true if object is still in memory, false if garbage collected
   */
  isLeaking(): Promise<boolean>;
}

Usage Examples:

// Monitor simple objects
const detector = new LeakDetector({ foo: "bar" });
const isLeaking = await detector.isLeaking();

// Monitor functions
const fn = () => console.log("test");
const fnDetector = new LeakDetector(fn);

// Monitor arrays
const arr = [1, 2, 3];
const arrDetector = new LeakDetector(arr);

// With configuration options
const detector = new LeakDetector(someObject, {
  shouldGenerateV8HeapSnapshot: false
});

Configuration Options

Options for customizing leak detection behavior.

interface LeakDetectorOptions {
  /**
   * Whether to generate V8 heap snapshots for more aggressive garbage collection
   * Heap snapshots provide more thorough GC but are slower to execute
   * @default true
   */
  shouldGenerateV8HeapSnapshot: boolean;
}

Error Handling

The LeakDetector throws errors in the following cases:

  • TypeError: When attempting to monitor primitive values (undefined, null, boolean, number, string, symbol)
    • Error format: "Primitives cannot leak memory. You passed a {type}: <{formatted_value}>"
// These will throw TypeError
new LeakDetector(null);        // TypeError: Primitives cannot leak memory. You passed a object: <null>
new LeakDetector(42);          // TypeError: Primitives cannot leak memory. You passed a number: <42>
new LeakDetector("string");    // TypeError: Primitives cannot leak memory. You passed a string: <"string">
new LeakDetector(true);        // TypeError: Primitives cannot leak memory. You passed a boolean: <true>
new LeakDetector(undefined);   // TypeError: Primitives cannot leak memory. You passed a undefined: <undefined>
new LeakDetector(Symbol());    // TypeError: Primitives cannot leak memory. You passed a symbol: <Symbol()>

Platform Requirements

  • Node.js: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0
  • JavaScript Features: ES2021.WeakRef (FinalizationRegistry support)
  • V8 Features: Heap snapshots, garbage collector access

Implementation Details

The leak detector uses several advanced JavaScript and Node.js features:

  • FinalizationRegistry: Tracks object lifecycle and executes cleanup callbacks when objects are garbage collected
  • V8 Heap Snapshots: Optional aggressive garbage collection through v8.getHeapSnapshot()
  • V8 Flags: Temporarily exposes and hides the garbage collector via --expose-gc and --no-expose-gc flags
  • setImmediate Ticks: Allows garbage collection cycles to complete before checking object status
  • VM Context: Executes garbage collection in a new context to avoid reference leaks