CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest-util

Collection of utility functions for Jest testing framework

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

garbage-collection.mddocs/

Garbage Collection Utilities

Memory management and cleanup utilities for test isolation and performance optimization. These utilities provide controlled property deletion and protection mechanisms to manage memory usage and prevent test interference.

Capabilities

Deletion Mode

Enumeration defining different modes for property deletion behavior in the garbage collection system.

/**
 * Deletion mode for garbage collection behavior
 */
type DeletionMode = 'soft' | 'off' | 'on';

Mode Descriptions:

  • 'off': Deletion completely disabled - properties are never deleted
  • 'soft': Wraps getters/setters with deprecation warnings instead of deleting
  • 'on': Actually deletes properties using the delete operator

Initialize Garbage Collection Utils

Initializes the garbage collection system with a specified deletion mode for the given global object.

/**
 * Initializes garbage collection system with specified deletion mode
 * @param globalObject - Global object to initialize GC system on
 * @param deletionMode - Mode for property deletion behavior
 * @throws Warning if mode already initialized with different setting
 */
function initializeGarbageCollectionUtils(
  globalObject: typeof globalThis,
  deletionMode: DeletionMode
): void;

Usage Examples:

import { initializeGarbageCollectionUtils } from "jest-util";

// Initialize GC system for test environment
initializeGarbageCollectionUtils(globalThis, 'soft');

// Different modes for different environments
if (process.env.NODE_ENV === 'test') {
  initializeGarbageCollectionUtils(globalThis, 'on'); // Aggressive cleanup
} else if (process.env.NODE_ENV === 'development') {
  initializeGarbageCollectionUtils(globalThis, 'soft'); // Warnings only
} else {
  initializeGarbageCollectionUtils(globalThis, 'off'); // No cleanup
}

// Jest test environment setup
function setupTestEnvironment() {
  initializeGarbageCollectionUtils(globalThis, 'soft');
  // Now all GC utilities will use soft deletion mode
}

Can Delete Properties

Type guard that determines if a value has properties that can be deleted through the garbage collection system.

/**
 * Type guard checking if value has deletable properties
 * @param value - Value to check for deletable properties
 * @returns true for objects and functions (excluding null)
 */
function canDeleteProperties(value: unknown): value is object;

Usage Examples:

import { canDeleteProperties } from "jest-util";

// Safe property deletion check
function cleanupValue(value: unknown) {
  if (canDeleteProperties(value)) {
    // TypeScript knows 'value' is an object here
    deleteProperties(value);
  }
}

// Test cleanup with type safety
const testValues = [
  { data: "test" },     // object - can delete
  () => {},             // function - can delete  
  null,                 // null - cannot delete
  "string",             // primitive - cannot delete
  42,                   // primitive - cannot delete
  undefined             // undefined - cannot delete
];

testValues.forEach(value => {
  if (canDeleteProperties(value)) {
    console.log("Can clean up:", typeof value);
    // Safely perform cleanup operations
  }
});

// Conditional cleanup in test teardown
function teardownTestObject(testObj: any) {
  if (canDeleteProperties(testObj)) {
    // Safe to attempt property deletion
    protectProperties(testObj, ['id', 'name']); // Protect essential props
    deleteProperties(testObj); // Clean up the rest
  }
}

Protect Properties

Protects specified object properties from garbage collection deletion, with optional recursive protection.

/**
 * Protects object properties from garbage collection deletion
 * @param value - Object to protect properties on
 * @param properties - Specific properties to protect (empty array = all properties)
 * @param depth - Nesting depth for recursive protection (default: 2)
 * @returns Whether protection was successfully applied
 */
function protectProperties<T>(
  value: T,
  properties?: Array<keyof T>,
  depth?: number
): boolean;

Usage Examples:

import { protectProperties, deleteProperties } from "jest-util";

// Protect specific properties
const testObject = {
  id: 1,
  name: "Test",
  tempData: "will be deleted", 
  cacheValue: "will be deleted"
};

// Protect only essential properties
protectProperties(testObject, ['id', 'name']);
deleteProperties(testObject);

// testObject now has: { id: 1, name: "Test" }
// tempData and cacheValue were deleted

// Protect all properties
const importantObject = { config: "value", settings: "data" };
protectProperties(importantObject); // Protects all properties
deleteProperties(importantObject); // Nothing gets deleted

// Recursive protection with depth control
const nestedObject = {
  level1: {
    level2: {
      level3: {
        data: "deep value"
      }
    },
    otherData: "value"
  },
  topLevel: "value"
};

// Protect with depth 2 (default)
protectProperties(nestedObject);
// Protects: topLevel, level1, level1.level2, level1.otherData
// Does NOT protect: level1.level2.level3 (depth 3)

// Custom depth protection
protectProperties(nestedObject, [], 3);
// Protects all properties up to 3 levels deep

// Test fixture protection
function createProtectedTestFixture() {
  const fixture = {
    essentialData: { id: 1, name: "test" },
    temporaryCache: new Map(),
    disposableResults: []
  };
  
  // Protect essential data but allow cleanup of cache and results
  protectProperties(fixture, ['essentialData']);
  
  return fixture;
}

Delete Properties

Deletes all non-protected properties from an object according to the current deletion mode.

/**
 * Deletes all non-protected properties from an object
 * @param value - Object to delete properties from
 * @remarks Respects protection settings and deletion mode
 */
function deleteProperties(value: unknown): void;

Usage Examples:

import { 
  deleteProperties, 
  protectProperties, 
  initializeGarbageCollectionUtils 
} from "jest-util";

// Basic cleanup
const testData = {
  result: "value",
  cache: new Map(),
  temp: "temporary"
};

deleteProperties(testData);
// All properties deleted (assuming no protection)

// Selective cleanup with protection
const userSession = {
  userId: 123,
  sessionId: "abc-123",
  tempData: { calculations: [1, 2, 3] },
  cache: new WeakMap()
};

protectProperties(userSession, ['userId', 'sessionId']);
deleteProperties(userSession);
// Only tempData and cache are deleted

// Test isolation cleanup
function isolateTest(testEnvironment: any) {
  // Protect test framework essentials
  protectProperties(testEnvironment, [
    'describe', 'it', 'expect', 'beforeEach', 'afterEach'
  ]);
  
  // Clean up everything else from previous tests
  deleteProperties(testEnvironment);
}

// Batch cleanup for test suites
function cleanupTestSuite(testObjects: any[]) {
  testObjects.forEach(obj => {
    if (canDeleteProperties(obj)) {
      deleteProperties(obj);
    }
  });
}

// Memory leak prevention
function preventMemoryLeaks() {
  const leakyObjects = [
    globalThis.testCache,
    globalThis.mockDatabase,
    globalThis.temporaryHandlers
  ];
  
  leakyObjects.forEach(obj => {
    if (obj && canDeleteProperties(obj)) {
      deleteProperties(obj);
    }
  });
}

Deletion Mode Behavior:

// Different behaviors based on deletion mode
initializeGarbageCollectionUtils(globalThis, 'off');
deleteProperties(someObject); // No properties deleted

initializeGarbageCollectionUtils(globalThis, 'soft');
deleteProperties(someObject); // Properties wrapped with deprecation warnings

initializeGarbageCollectionUtils(globalThis, 'on'); 
deleteProperties(someObject); // Properties actually deleted

Complete Workflow Example

import {
  initializeGarbageCollectionUtils,
  protectProperties,
  canDeleteProperties,
  deleteProperties
} from "jest-util";

// 1. Initialize GC system
initializeGarbageCollectionUtils(globalThis, 'soft');

// 2. Create test environment
const testEnvironment = {
  // Essential test framework functions
  describe: globalThis.describe,
  it: globalThis.it,
  expect: globalThis.expect,
  
  // Test data that should be cleaned up
  testResults: [],
  mockDatabase: new Map(),
  temporaryFiles: [],
  
  // Configuration that should persist
  testConfig: { timeout: 5000, verbose: true }
};

// 3. Protect essential properties
protectProperties(testEnvironment, [
  'describe', 'it', 'expect', 'testConfig'
]);

// 4. Run tests (test data accumulates)
// ... test execution ...

// 5. Clean up after test suite
if (canDeleteProperties(testEnvironment)) {
  deleteProperties(testEnvironment);
  // Only testResults, mockDatabase, temporaryFiles are deleted
  // describe, it, expect, testConfig remain intact
}

// 6. Verify cleanup
console.log(testEnvironment);
// {
//   describe: [Function],
//   it: [Function], 
//   expect: [Function],
//   testConfig: { timeout: 5000, verbose: true }
// }

Performance Considerations

  • Protection Overhead: Property protection adds metadata tracking - use sparingly for large objects
  • Deletion Modes: 'soft' mode has higher overhead due to wrapper functions
  • Recursive Protection: Deep protection can be expensive - limit depth for large nested objects
  • Memory Usage: Protected properties consume additional memory for tracking metadata

Integration with Jest

// Jest test environment setup
export default class CustomTestEnvironment {
  async setup() {
    // Initialize GC with soft mode for development
    initializeGarbageCollectionUtils(this.global, 'soft');
    
    // Protect Jest globals
    protectProperties(this.global, [
      'describe', 'it', 'test', 'expect', 
      'beforeEach', 'afterEach', 'beforeAll', 'afterAll'
    ]);
  }
  
  async teardown() {
    // Clean up test artifacts while preserving Jest globals
    if (canDeleteProperties(this.global)) {
      deleteProperties(this.global);
    }
  }
}

docs

data-manipulation.md

error-handling.md

file-system.md

garbage-collection.md

global-environment.md

index.md

module-loading.md

string-path.md

terminal.md

type-checking.md

tile.json