Jest Environment Base Class and Types for creating custom test execution environments
npx @tessl/cli install tessl/npm-jest--environment@30.1.0Jest Environment provides the base class and TypeScript type definitions for Jest test environments. It defines the foundation for all Jest test execution environments (Node.js, JSDOM, etc.), establishing the interface for setting up isolated execution contexts for tests.
npm install @jest/environmentimport {
JestEnvironment,
EnvironmentContext,
JestEnvironmentConfig,
ModuleWrapper,
Jest
} from "@jest/environment";For CommonJS:
const {
JestEnvironment,
EnvironmentContext,
JestEnvironmentConfig,
ModuleWrapper,
Jest
} = require("@jest/environment");import {
JestEnvironment,
EnvironmentContext,
JestEnvironmentConfig
} from "@jest/environment";
import { LegacyFakeTimers, ModernFakeTimers } from "@jest/fake-timers";
import { ModuleMocker } from "jest-mock";
// Custom environment implementation
class MyCustomEnvironment extends JestEnvironment {
constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
super(config, context);
// Initialize custom global object
this.global = {} as any;
this.fakeTimers = null;
this.fakeTimersModern = null;
this.moduleMocker = null;
}
async setup(): Promise<void> {
// Setup environment before tests run
this.global.myCustomGlobal = "test value";
}
async teardown(): Promise<void> {
// Cleanup after tests complete
this.global = null as any;
}
getVmContext() {
// Return VM context for code execution
return null;
}
}Jest Environment is built around several key components:
JestEnvironment class that defines the interfaceJestEnvironmentConfig and EnvironmentContext for initializationModuleWrapper type for Node.js module wrappingJest interface definition for test environmentsThe core abstract class that all Jest environments must implement.
/**
* Abstract base class for Jest test environments
* @template Timer - Type for timer implementation (default: unknown)
*/
declare class JestEnvironment<Timer = unknown> {
constructor(config: JestEnvironmentConfig, context: EnvironmentContext);
/** Global object for the test environment */
global: Global.Global;
/** Legacy fake timers implementation */
fakeTimers: LegacyFakeTimers<Timer> | null;
/** Modern fake timers implementation */
fakeTimersModern: ModernFakeTimers | null;
/** Module mocking utility */
moduleMocker: ModuleMocker | null;
/** Get VM context for code execution */
getVmContext(): Context | null;
/** Setup the environment before test execution */
setup(): Promise<void>;
/** Cleanup the environment after test execution */
teardown(): Promise<void>;
/** Optional test event handler */
handleTestEvent?: Circus.EventHandler;
/** Optional export conditions provider */
exportConditions?: () => Array<string>;
}Configuration types for initializing Jest environments.
/**
* Configuration object passed to Jest environments
*/
interface JestEnvironmentConfig {
/** Project-specific Jest configuration */
projectConfig: Config.ProjectConfig;
/** Global Jest configuration */
globalConfig: Config.GlobalConfig;
}
/**
* Configuration context passed to environment constructors
*/
interface EnvironmentContext {
/** Console instance for the test environment */
console: Console;
/** Document block pragmas from test files */
docblockPragmas: Record<string, string | Array<string>>;
/** Path to the test file being executed */
testPath: string;
}Types for integrating with Node.js module system during test execution.
/**
* Function signature for wrapping Node.js modules during test execution
*/
type ModuleWrapper = (
this: Module['exports'],
module: Module,
exports: Module['exports'],
require: Module['require'],
__dirname: string,
__filename: Module['filename'],
jest?: Jest,
...sandboxInjectedGlobals: Array<Global.Global[keyof Global.Global]>
) => unknown;
/**
* Extended ImportMeta interface with Jest global for ESM modules
*/
interface JestImportMeta extends ImportMeta {
jest: Jest;
}
/**
* Alias for Node.js NodeModule type
*/
type Module = NodeModule;Complete Jest global API interface providing all Jest methods and utilities.
/**
* Complete Jest global API interface
*/
interface Jest {
// Timer Control Methods
/** Advance timers by milliseconds */
advanceTimersByTime(msToRun: number): void;
/** Async timer advancement */
advanceTimersByTimeAsync(msToRun: number): Promise<void>;
/** Advance to next animation frame */
advanceTimersToNextFrame(): void;
/** Advance to next timer */
advanceTimersToNextTimer(steps?: number): void;
/** Async advance to next timer */
advanceTimersToNextTimerAsync(steps?: number): Promise<void>;
/** Clear all pending timers */
clearAllTimers(): void;
/** Get count of pending timers */
getTimerCount(): number;
/** Get real system time when mocking time */
getRealSystemTime(): number;
/** Get current fake timer time */
now(): number;
/** Execute all pending timers */
runAllTimers(): void;
/** Async execute all pending timers */
runAllTimersAsync(): Promise<void>;
/** Execute only currently pending timers */
runOnlyPendingTimers(): void;
/** Async execute only pending timers */
runOnlyPendingTimersAsync(): Promise<void>;
/** Execute all setImmediate callbacks (legacy only) */
runAllImmediates(): void;
/** Execute all process.nextTick callbacks */
runAllTicks(): void;
/** Set fake system time */
setSystemTime(now?: number | Date): void;
/** Enable fake timers */
useFakeTimers(fakeTimersConfig?: Config.FakeTimersConfig | Config.LegacyFakeTimersConfig): Jest;
/** Disable fake timers */
useRealTimers(): Jest;
// Mock Control Methods
/** Disable automatic mocking */
autoMockOff(): Jest;
/** Enable automatic mocking */
autoMockOn(): Jest;
/** Clear all mock calls/results */
clearAllMocks(): Jest;
/** Reset all mocks */
resetAllMocks(): Jest;
/** Restore all mocks to original implementations */
restoreAllMocks(): Jest;
/** Disable automatic mocking */
disableAutomock(): Jest;
/** Enable automatic mocking */
enableAutomock(): Jest;
// Module Mocking Methods
/** Mock a module */
mock<T = unknown>(moduleName: string, moduleFactory?: () => T, options?: {virtual?: boolean}): Jest;
/** Unmock a module */
unmock(moduleName: string): Jest;
/** Mock without hoisting */
doMock<T = unknown>(moduleName: string, moduleFactory?: () => T, options?: {virtual?: boolean}): Jest;
/** Don't mock without hoisting */
dontMock(moduleName: string): Jest;
/** Unmock module and dependencies */
deepUnmock(moduleName: string): Jest;
/** Mock ES module */
unstable_mockModule<T = unknown>(moduleName: string, moduleFactory: () => T | Promise<T>, options?: {virtual?: boolean}): Jest;
/** Unmock ES module */
unstable_unmockModule(moduleName: string): Jest;
/** Set mock implementation */
setMock(moduleName: string, moduleExports: unknown): Jest;
/** Require actual module */
requireActual<T = unknown>(moduleName: string): T;
/** Require mocked module */
requireMock<T = unknown>(moduleName: string): T;
/** Create mock from module */
createMockFromModule<T = unknown>(moduleName: string): Mocked<T>;
/** Register mock generation callback */
onGenerateMock<T>(cb: (modulePath: string, moduleMock: T) => T): Jest;
// Module System Methods
/** Reset module registry */
resetModules(): Jest;
/** Execute function with isolated modules */
isolateModules(fn: () => void): Jest;
/** Async isolate modules */
isolateModulesAsync(fn: () => Promise<void>): Promise<void>;
// Mock Function Methods
/** Create mock function */
fn: ModuleMocker['fn'];
/** Check if function is mocked */
isMockFunction: ModuleMocker['isMockFunction'];
/** Create spy on object method */
spyOn: ModuleMocker['spyOn'];
/** Type-safe mock wrapping */
mocked: ModuleMocker['mocked'];
/** Replace object property */
replaceProperty: ModuleMocker['replaceProperty'];
// Test Control Methods
/** Set test timeout */
setTimeout(timeout: number): Jest;
/** Set test retry behavior */
retryTimes(
numRetries: number,
options?: {
logErrorsBeforeRetry?: boolean;
retryImmediately?: boolean;
waitBeforeRetry?: number;
}
): Jest;
// Utility Methods
/** Get random seed value */
getSeed(): number;
/** Check if environment is torn down */
isEnvironmentTornDown(): boolean;
}// Re-exported from dependencies
import type { Context } from 'vm';
import type { LegacyFakeTimers, ModernFakeTimers } from '@jest/fake-timers';
import type { Circus, Config, Global } from '@jest/types';
import type { Mocked, ModuleMocker } from 'jest-mock';