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

terminal.mddocs/

Terminal Interaction

Terminal and TTY interaction utilities for Jest's interactive features and output control. These utilities manage terminal state detection, output clearing, and special character handling across different platforms and environments.

Capabilities

Clear Line

Clears the current line in a TTY stream using ANSI escape codes, commonly used for updating progress indicators and dynamic output.

/**
 * Clears the current line in a TTY stream
 * @param stream - The TTY write stream to clear
 */
function clearLine(stream: WriteStream): void;

Usage Examples:

import { clearLine } from "jest-util";

// Clear current line in stdout
clearLine(process.stdout);

// Clear current line in stderr  
clearLine(process.stderr);

// Progress indicator with line clearing
function showProgress(current: number, total: number) {
  clearLine(process.stdout);
  process.stdout.write(`Progress: ${current}/${total} (${Math.round(current/total * 100)}%)`);
}

// Jest test runner progress
function updateTestProgress(completed: number, total: number) {
  if (process.stdout.isTTY) {
    clearLine(process.stdout);
    process.stdout.write(`Tests: ${completed}/${total} completed`);
  }
}

// Dynamic status updates
let dots = 0;
const statusInterval = setInterval(() => {
  if (process.stdout.isTTY) {
    clearLine(process.stdout);
    process.stdout.write(`Running tests${'.'.repeat(dots % 4)}`);
    dots++;
  }
}, 500);

Behavior:

  • Only operates on TTY streams - no-op for non-TTY streams
  • Sends ANSI escape sequence \r\x1b[K to clear line
  • Positions cursor at beginning of line after clearing

Is Interactive

Boolean constant indicating whether the current environment supports interactive terminal features.

/**
 * Boolean indicating if environment supports interactive features
 */
const isInteractive: boolean;

Usage Examples:

import { isInteractive } from "jest-util";

// Conditional interactive features
if (isInteractive) {
  console.log("Running in interactive mode");
  // Show progress bars, colored output, etc.
} else {
  console.log("Running in non-interactive mode"); 
  // Plain text output for CI/CD
}

// Jest watch mode detection
function shouldEnableWatchMode(): boolean {
  return isInteractive && !process.env.CI;
}

// Progress reporting
function reportProgress(current: number, total: number) {
  if (isInteractive) {
    // Show dynamic progress bar
    clearLine(process.stdout);
    process.stdout.write(`[${'='.repeat(current)}${' '.repeat(total-current)}] ${current}/${total}`);
  } else {
    // Log discrete progress updates
    if (current % 10 === 0) {
      console.log(`Progress: ${current}/${total}`);
    }
  }
}

Detection Logic:

  • Returns false if running in CI environment (detected via ci-info)
  • Returns false if process.stdout is null
  • Returns false if TERM environment variable is 'dumb'
  • Returns true if process.stdout.isTTY is true
  • Otherwise returns false

Special Characters

Collection of Unicode characters and ANSI sequences for consistent terminal output across platforms.

/**
 * Collection of special characters for terminal output
 */
const specialChars: {
  /** Arrow character for indicating direction or selection */
  ARROW: string;
  /** Status icons for test results */
  ICONS: {
    /** Cross mark for failed tests */
    failed: string;
    /** Circle for pending tests */ 
    pending: string;
    /** Check mark for successful tests */
    success: string;
    /** Pencil for todo items */
    todo: string;
  };
  /** ANSI clear screen sequence */
  CLEAR: string;
};

Usage Examples:

import { specialChars } from "jest-util";

// Test result formatting
function formatTestResult(status: 'passed' | 'failed' | 'pending' | 'todo', name: string) {
  let icon: string;
  switch (status) {
    case 'passed': icon = specialChars.ICONS.success; break;
    case 'failed': icon = specialChars.ICONS.failed; break;
    case 'pending': icon = specialChars.ICONS.pending; break;
    case 'todo': icon = specialChars.ICONS.todo; break;
  }
  
  return `${icon} ${name}`;
}

// Examples:
// formatTestResult('passed', 'should add numbers') → "✓ should add numbers"
// formatTestResult('failed', 'should handle errors') → "✗ should handle errors"

// Navigation indicators
function showSelected(items: string[], selectedIndex: number) {
  items.forEach((item, index) => {
    const prefix = index === selectedIndex ? specialChars.ARROW : '  ';
    console.log(`${prefix} ${item}`);
  });
}

// Clear screen for fresh output
function clearScreen() {
  process.stdout.write(specialChars.CLEAR);
}

// Test suite header
function printTestSuiteHeader() {
  clearScreen();
  console.log(`${specialChars.ICONS.success} Jest Test Suite`);
  console.log(`${specialChars.ARROW} Running tests...`);
}

Character Values:

  • ARROW: (bullet point with spaces)
  • ICONS.failed: Platform-specific cross mark (✗ or ×)
  • ICONS.pending: (hollow circle)
  • ICONS.success: Platform-specific check mark (✓ or √)
  • ICONS.todo: (pencil)
  • CLEAR: Platform-specific ANSI clear sequence

Pre-Run Message

Utilities for displaying and managing the "Determining test suites to run..." message during Jest's initialization phase.

/**
 * Pre-run message utilities for Jest initialization
 */
const preRunMessage: {
  /** Display the pre-run message in interactive mode */
  print(stream: WriteStream): void;
  /** Clear the pre-run message in interactive mode */
  remove(stream: WriteStream): void;
};

Usage Examples:

import { preRunMessage } from "jest-util";

// Jest initialization sequence
function initializeTestRun() {
  // Show loading message
  preRunMessage.print(process.stdout);
  
  // Perform test discovery and setup
  await discoverTestFiles();
  await setupTestEnvironment();
  
  // Clear loading message before starting tests
  preRunMessage.remove(process.stdout);
  
  console.log("Starting test execution...");
}

// Custom loading sequence
function showInitializationProgress() {
  preRunMessage.print(process.stdout);
  
  setTimeout(() => {
    preRunMessage.remove(process.stdout);
    console.log("Initialization complete!");
  }, 2000);
}

// Conditional message display
function conditionalPreRunMessage() {
  if (process.env.VERBOSE !== 'true') {
    preRunMessage.print(process.stdout);
    
    // Later, after setup is complete
    preRunMessage.remove(process.stdout);
  }
}

Behavior:

  • Interactive Mode Only: Messages are only displayed when isInteractive is true
  • Non-TTY Safe: No output occurs on non-TTY streams
  • Message Content: Displays "Determining test suites to run..." with appropriate styling
  • Clean Removal: remove() clears the message line completely

Types

// Node.js WriteStream interface
interface WriteStream {
  write(chunk: any): boolean;
  isTTY?: boolean;
}

Platform Compatibility:

  • Windows: Uses appropriate Unicode characters and ANSI sequences
  • Unix/Linux: Uses standard terminal control sequences
  • CI Environments: Automatically detects and disables interactive features
  • SSH Sessions: Respects TTY detection for remote terminal sessions

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