or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-execution.mdcustom-runner.mdindex.mdtest-runner.mdworker-management.md
tile.json

tessl/npm-jest-runner

Jest's test runner responsible for orchestrating test execution, managing worker processes, and coordinating parallel test runs

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

To install, run

npx @tessl/cli install tessl/npm-jest-runner@30.1.0

index.mddocs/

Jest Runner

Jest Runner is the core test execution engine of the Jest testing framework, responsible for orchestrating test execution, managing worker processes, and coordinating parallel test runs. It provides both serial and parallel test execution modes, manages worker process lifecycles, and implements an event-driven architecture for real-time test progress reporting.

Package Information

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

Core Imports

import TestRunner from "jest-runner";
import { 
  CallbackTestRunner, 
  EmittingTestRunner,
  type CallbackTestRunnerInterface,
  type EmittingTestRunnerInterface,
  type TestRunnerOptions,
  type TestRunnerContext,
  type TestFramework,
  type ErrorWithCode,
  type JestTestRunner,
  type OnTestStart,
  type OnTestFailure,
  type OnTestSuccess,
  type UnsubscribeFn,
  type Test,
  type TestEvents,
  type Config,
  type TestWatcher
} from "jest-runner";

For CommonJS:

const TestRunner = require("jest-runner");
const { 
  CallbackTestRunner, 
  EmittingTestRunner,
  // Types are not available in CommonJS, use JSDoc for type hints
} = require("jest-runner");

Basic Usage

import TestRunner from "jest-runner";
import { TestWatcher } from "jest-watcher";
import type { Test } from "@jest/test-result";
import type { Config } from "@jest/types";

// Create test runner instance
const globalConfig: Config.GlobalConfig = { /* Jest configuration */ };
const context = { 
  changedFiles: new Set<string>(),
  sourcesRelatedToTestsInChangedFiles: new Set<string>()
};
const runner = new TestRunner(globalConfig, context);

// Prepare tests
const tests: Test[] = [
  {
    path: "/path/to/test1.js",
    context: { /* test context */ }
  }
];

// Set up watcher
const watcher = new TestWatcher({ isWatchMode: false });

// Run tests
await runner.runTests(tests, watcher, { serial: false });

// Listen to events
runner.on('test-file-start', ([test]) => {
  console.log(`Starting test: ${test.path}`);
});

runner.on('test-file-success', ([test, result]) => {
  console.log(`Test passed: ${test.path}`);
});

Architecture

Jest Runner is built around several key components:

  • TestRunner Class: The main default export implementing EmittingTestRunner for event-driven test execution
  • Abstract Base Classes: CallbackTestRunner and EmittingTestRunner for creating custom test runners
  • Worker Process Management: Parallel test execution using jest-worker with configurable worker limits
  • Event System: Real-time progress reporting through typed event emissions
  • Test Execution Engine: Core runTest function handling individual test file execution
  • Memory Management: Leak detection and configurable memory limits for worker processes

Capabilities

Test Runner Implementation

The main TestRunner class providing both serial and parallel test execution with event-driven progress reporting.

export default class TestRunner extends EmittingTestRunner {
  constructor(globalConfig: Config.GlobalConfig, context: TestRunnerContext);
  
  runTests(
    tests: Array<Test>,
    watcher: TestWatcher,
    options: TestRunnerOptions
  ): Promise<void>;
  
  on<Name extends keyof TestEvents>(
    eventName: Name,
    listener: (eventData: TestEvents[Name]) => void | Promise<void>
  ): UnsubscribeFn;
}

Test Runner Implementation

Custom Test Runner Framework

Abstract base classes and interfaces for building custom test runners with both callback and event-driven patterns.

abstract class CallbackTestRunner extends BaseTestRunner {
  readonly supportsEventEmitters = false;
  
  abstract runTests(
    tests: Array<Test>,
    watcher: TestWatcher,
    onStart: OnTestStart,
    onResult: OnTestSuccess,
    onFailure: OnTestFailure,
    options: TestRunnerOptions
  ): Promise<void>;
}

abstract class EmittingTestRunner extends BaseTestRunner {
  readonly supportsEventEmitters = true;
  
  abstract runTests(
    tests: Array<Test>,
    watcher: TestWatcher,
    options: TestRunnerOptions
  ): Promise<void>;
  
  abstract on<Name extends keyof TestEvents>(
    eventName: Name,
    listener: (eventData: TestEvents[Name]) => void | Promise<void>
  ): UnsubscribeFn;
}

Custom Test Runner Framework

Core Test Execution

Internal test execution engine used by the TestRunner class. The runTest function handles individual test file execution with environment setup, framework integration, and result collection.

Note: This is an internal API used by TestRunner and not directly exported for public use.

Core Test Execution

Worker Process Management

Internal worker process management system for parallel test execution. These functions handle worker setup, test execution, and communication between main and worker processes.

Note: These are internal APIs used by TestRunner's parallel execution mode and not directly exported for public use.

Worker Process Management

Core Types

interface TestRunnerOptions {
  serial: boolean;
}

interface TestRunnerContext {
  changedFiles?: Set<string>;
  sourcesRelatedToTestsInChangedFiles?: Set<string>;
}

interface TestContext {
  config: Config.ProjectConfig;
  moduleMap: ModuleMap;
  resolver: Resolver;
}

// Re-exported from @jest/test-result
interface Test {
  path: string;
  context: TestContext;
}

interface TestEvents {
  'test-file-start': [Test];
  'test-file-success': [Test, TestResult];
  'test-file-failure': [Test, SerializableError];
}

interface TestResult {
  console: ConsoleBuffer;
  coverage?: CoverageMap;
  displayName?: Config.DisplayName;
  leaks: boolean;
  memoryUsage?: number;
  numFailingTests: number;
  numPassingTests: number;
  numPendingTests: number;
  numTodoTests: number;
  perfStats: TestPerformanceStats;
  skipped: boolean;
  testFilePath: string;
  testResults: Array<AssertionResult>;
  v8Coverage?: V8CoverageResult[];
}

interface SerializableError {
  message: string;
  stack?: string;
  type: string;
  code?: string;
}

interface TestPerformanceStats {
  start: number;
  end: number;
  runtime: number;
  slow: boolean;
  loadTestEnvironmentStart: number;
  loadTestEnvironmentEnd: number;
  setupFilesStart: number;
  setupFilesEnd: number;
}

type TestFramework = (
  globalConfig: Config.GlobalConfig,
  config: Config.ProjectConfig,
  environment: JestEnvironment,
  runtime: RuntimeType,
  testPath: string,
  sendMessageToJest?: TestFileEvent
) => Promise<TestResult>;

type ErrorWithCode = Error & { code?: string };

type OnTestStart = (test: Test) => Promise<void>;
type OnTestFailure = (test: Test, serializableError: SerializableError) => Promise<void>;
type OnTestSuccess = (test: Test, testResult: TestResult) => Promise<void>;
type UnsubscribeFn = () => void;
type JestTestRunner = CallbackTestRunner | EmittingTestRunner;

type TestFileEvent = (
  eventName: string,
  args: Array<any>
) => void | Promise<void>;

interface JestEnvironment {
  global: typeof globalThis;
  getVmContext(): vm.Context | null;
  setup(): Promise<void>;
  teardown(): Promise<void>;
}

interface AssertionResult {
  ancestorTitles: Array<string>;
  duration?: number;
  failureDetails: Array<unknown>;
  failureMessages: Array<string>;
  fullName: string;
  invocations?: number;
  location?: Callsite;
  numPassingAsserts: number;
  retryReasons?: Array<string>;
  status: 'passed' | 'failed' | 'skipped' | 'pending' | 'todo' | 'disabled';
  title: string;
}

interface ConsoleBuffer extends Array<LogEntry> {}

interface LogEntry {
  message: string;
  origin: string;
  type: LogType;
}

type LogType = 'assert' | 'count' | 'debug' | 'dir' | 'dirxml' | 'error' | 'group' | 'groupCollapsed' | 'groupEnd' | 'info' | 'log' | 'time' | 'warn';

interface Callsite {
  column: number;
  line: number;
}

// Re-exported types from dependencies - use these imports to access them
// import type { ModuleMap, Resolver, RuntimeType } from '@jest/types';
// import type { CoverageMap, V8CoverageResult } from 'istanbul-lib-coverage';