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

data-manipulation.mddocs/

Data Manipulation

Utilities for copying, transforming, and manipulating data structures commonly used in test scenarios. These functions provide safe and reliable data operations that handle edge cases like circular references and complex object structures.

Capabilities

Deep Cyclic Copy

Creates a deep copy of objects while safely handling circular references, with configurable options for property filtering and prototype preservation.

/**
 * Deep copies objects while handling circular references
 * @param value - Value to copy
 * @param options - Copy options for customizing behavior
 * @param cycles - Internal cycle tracking (used recursively)
 * @returns Deep copy of the input value
 */
function deepCyclicCopy<T>(
  value: T, 
  options?: DeepCyclicCopyOptions, 
  cycles?: WeakMap<any, any>
): T;

interface DeepCyclicCopyOptions {
  /** Property names to skip during copying */
  blacklist?: Set<string>;
  /** Whether to preserve prototype chain */
  keepPrototype?: boolean;
}

Usage Examples:

import { deepCyclicCopy } from "jest-util";

// Basic deep copying
const original = {
  user: { name: "Alice", age: 30 },
  settings: { theme: "dark", notifications: true },
  data: [1, 2, { nested: "value" }]
};

const copy = deepCyclicCopy(original);
copy.user.name = "Bob"; // original.user.name remains "Alice"

// Handling circular references safely
const circularObj: any = { name: "test" };
circularObj.self = circularObj; // Creates circular reference

const safeCopy = deepCyclicCopy(circularObj);
console.log(safeCopy.self === safeCopy); // true - circular reference preserved

// Using blacklist to skip sensitive properties
const sensitiveData = {
  publicInfo: { name: "Alice" },
  password: "secret123",
  token: "jwt-token-here",
  internalId: "internal-use-only"
};

const publicCopy = deepCyclicCopy(sensitiveData, {
  blacklist: new Set(["password", "token", "internalId"])
});
// publicCopy only contains publicInfo

// Preserving prototype chain
class TestClass {
  method() { return "test"; }
}
const instance = new TestClass();
instance.data = { value: 42 };

const copyWithPrototype = deepCyclicCopy(instance, { keepPrototype: true });
console.log(copyWithPrototype instanceof TestClass); // true
console.log(copyWithPrototype.method()); // "test"

const copyWithoutPrototype = deepCyclicCopy(instance, { keepPrototype: false });
console.log(copyWithoutPrototype instanceof TestClass); // false

Advanced Usage:

// Test fixture preparation
function createTestFixture() {
  const baseData = {
    users: [
      { id: 1, name: "Alice", posts: [] },
      { id: 2, name: "Bob", posts: [] }
    ],
    metadata: { version: "1.0", timestamp: Date.now() }
  };
  
  // Create circular references for realistic data
  baseData.users[0].posts.push({ author: baseData.users[0], content: "Hello" });
  
  return baseData;
}

// Each test gets an independent copy
test("user modification", () => {
  const testData = deepCyclicCopy(createTestFixture());
  testData.users[0].name = "Charlie";
  // Original fixture remains unchanged
});

// Mock object preparation with prototype preservation
class DatabaseConnection {
  query(sql: string) { return []; }
  close() { }
}

const mockConnection = deepCyclicCopy(new DatabaseConnection(), {
  keepPrototype: true
});
// mockConnection retains DatabaseConnection methods

Convert Descriptor To String

Converts various descriptor types (functions, numbers, strings) to their string representation, commonly used for test output and error messages.

/**
 * Converts various descriptor types to string representation
 * @param descriptor - Function, number, string, or undefined to convert
 * @returns String representation of the descriptor
 * @throws Error for invalid descriptor types
 */
function convertDescriptorToString(
  descriptor: Global.BlockNameLike | undefined
): string;

Usage Examples:

import { convertDescriptorToString } from "jest-util";

// Function descriptors
function testFunction() { return "test"; }
console.log(convertDescriptorToString(testFunction)); // "testFunction"

const anonymousFunction = () => {};
console.log(convertDescriptorToString(anonymousFunction)); // function name or "[anonymous]"

// String descriptors
console.log(convertDescriptorToString("test suite")); // "test suite"
console.log(convertDescriptorToString("")); // ""

// Number descriptors
console.log(convertDescriptorToString(42)); // "42"
console.log(convertDescriptorToString(0)); // "0"

// Undefined descriptor
console.log(convertDescriptorToString(undefined)); // ""

// Jest test context usage
function describeTestBlock(descriptor: Global.BlockNameLike | undefined) {
  const name = convertDescriptorToString(descriptor);
  console.log(`Running test block: ${name || "unnamed"}`);
}

// Test suite generation
const testSuites = [
  testFunction,
  "Integration Tests",
  42, // Test group number
  undefined
];

testSuites.forEach(suite => {
  const suiteName = convertDescriptorToString(suite);
  console.log(`Test Suite: ${suiteName}`);
});

Error Handling:

// Invalid descriptor types throw errors
try {
  convertDescriptorToString({}); // Object is not a valid descriptor
} catch (error) {
  console.log("Invalid descriptor type");
}

try {
  convertDescriptorToString([]); // Array is not a valid descriptor
} catch (error) {
  console.log("Invalid descriptor type");
}

Types

interface DeepCyclicCopyOptions {
  /** Property names to skip during copying */
  blacklist?: Set<string>;
  /** Whether to preserve prototype chain */
  keepPrototype?: boolean;
}

// From @jest/types
type Global.BlockNameLike = string | number | Function | undefined;

Performance Considerations:

  • deepCyclicCopy: Uses WeakMap for cycle detection, providing O(1) lookups
  • Blacklist checking: Property filtering is optimized for large blacklists using Set
  • Prototype handling: Prototype preservation adds minimal overhead when enabled
  • Memory usage: Circular reference tracking scales with object complexity

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