or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-mock-generation.mdindex.mdmock-functions.mdspy-operations.mdtype-system.md
tile.json

tessl/npm-jest-mock

Comprehensive mock function library providing sophisticated mocking, spying, and property replacement capabilities for JavaScript and TypeScript testing

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

To install, run

npx @tessl/cli install tessl/npm-jest-mock@30.0.0

index.mddocs/

Jest Mock

Jest Mock is a comprehensive mock function library that provides sophisticated mock capabilities for testing JavaScript and TypeScript applications. It includes the ModuleMocker class for advanced mocking scenarios, as well as convenient utility functions for common mock operations like spying, function mocking, and property replacement.

Package Information

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

Core Imports

import { fn, spyOn, mocked, replaceProperty, ModuleMocker } from "jest-mock";

For CommonJS:

const { fn, spyOn, mocked, replaceProperty, ModuleMocker } = require("jest-mock");

Basic Usage

import { fn, spyOn, replaceProperty } from "jest-mock";

// Create a mock function
const mockFn = fn((x: number) => x * 2);
mockFn(5); // Returns 10
console.log(mockFn.mock.calls); // [[5]]

// Spy on an object method
const obj = { calculate: (a: number, b: number) => a + b };
const spy = spyOn(obj, 'calculate');
obj.calculate(2, 3); // Returns 5
console.log(spy.mock.calls); // [[2, 3]]

// Replace a property temporarily
const config = { apiUrl: 'https://api.example.com' };
const replaced = replaceProperty(config, 'apiUrl', 'https://test.example.com');
console.log(config.apiUrl); // 'https://test.example.com'
replaced.restore();
console.log(config.apiUrl); // 'https://api.example.com'

Architecture

Jest Mock is built around several key components:

  • Mock Functions: Core mock function implementation with call tracking and behavior control
  • Spy System: Non-invasive observation and replacement of existing methods and properties
  • Metadata System: Recursive object analysis for generating mocks from existing objects
  • ModuleMocker Class: Low-level API for advanced mocking scenarios and custom mock generation
  • Type System: Full TypeScript support with generic type preservation and utility types

Capabilities

Mock Function Creation

Creates standalone mock functions with comprehensive call tracking, return value control, and implementation management.

function fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;

interface Mock<T extends FunctionLike = UnknownFunction> extends Function, MockInstance<T> {
  new (...args: Parameters<T>): ReturnType<T>;
  (...args: Parameters<T>): ReturnType<T>;
}

type FunctionLike = (...args: any) => any;
type UnknownFunction = (...args: Array<unknown>) => unknown;

Mock Functions

Spy Operations

Non-invasive spying and replacement of object methods and properties with automatic restoration capabilities.

function spyOn<T extends object, K extends keyof T>(
  object: T,
  methodKey: K,
  accessType?: 'get' | 'set'
): MockInstance;

function replaceProperty<T extends object, K extends keyof T>(
  object: T,
  propertyKey: K,
  value: T[K]
): Replaced<T[K]>;

interface Replaced<T = unknown> {
  restore(): void;
  replaceValue(value: T): this;
}

Spy Operations

Type System and Utilities

Comprehensive TypeScript utilities for type-safe mocking with generic preservation and utility functions.

function mocked<T extends object>(source: T, options?: {shallow?: boolean}): Mocked<T> | MockedShallow<T>;

type Mocked<T> = T extends ClassLike
  ? MockedClass<T>
  : T extends FunctionLike
    ? MockedFunction<T>
    : T extends object
      ? MockedObject<T>
      : T;

type ClassLike = new (...args: any) => any;

Type System

Advanced Mock Generation

Low-level ModuleMocker class for metadata-driven mock generation and advanced mocking scenarios.

class ModuleMocker {
  constructor(global: typeof globalThis);
  generateFromMetadata<T>(metadata: MockMetadata<T>): Mocked<T>;
  getMetadata<T>(component: T, _refs?: Map<T, number>): MockMetadata<T> | null;
  fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;
  spyOn<T extends object, K extends keyof T>(object: T, methodKey: K, accessType?: 'get' | 'set'): MockInstance;
  replaceProperty<T extends object, K extends keyof T>(object: T, propertyKey: K, value: T[K]): Replaced<T[K]>;
  clearAllMocks(): void;
  resetAllMocks(): void;
  restoreAllMocks(): void;
  isMockFunction(fn: unknown): fn is Mock<UnknownFunction>;
  mocked<T extends object>(source: T, options?: {shallow?: boolean}): Mocked<T> | MockedShallow<T>;
}

Advanced Mock Generation

Global Types

type MockMetadataType = 'object' | 'array' | 'regexp' | 'function' | 'constant' | 'collection' | 'null' | 'undefined';

interface MockMetadata<T, MetadataType = MockMetadataType> {
  ref?: number;
  members?: Record<string, MockMetadata<T>>;
  mockImpl?: T;
  name?: string;
  refID?: number;
  type?: MetadataType;
  value?: T;
  length?: number;
}

interface MockInstance<T extends FunctionLike = UnknownFunction> extends Disposable {
  _isMockFunction: true;
  _protoImpl: Function;
  mock: MockFunctionState<T>;
  getMockImplementation(): T | undefined;
  getMockName(): string;
  mockClear(): this;
  mockReset(): this;
  mockRestore(): void;
  mockImplementation(fn: T): this;
  mockImplementationOnce(fn: T): this;
  withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>;
  withImplementation(fn: T, callback: () => void): void;
  mockName(name: string): this;
  mockReturnThis(): this;
  mockReturnValue(value: ReturnType<T>): this;
  mockReturnValueOnce(value: ReturnType<T>): this;
  mockResolvedValue<U>(value: U): this; // where ReturnType<T> extends PromiseLike<U>
  mockResolvedValueOnce<U>(value: U): this; // where ReturnType<T> extends PromiseLike<U>
  mockRejectedValue(value: unknown): this; // for Promise-returning functions
  mockRejectedValueOnce(value: unknown): this; // for Promise-returning functions
}

interface MockFunctionState<T extends FunctionLike = UnknownFunction> {
  calls: Array<Parameters<T>>;
  instances: Array<ReturnType<T>>;
  contexts: Array<ThisParameterType<T>>;
  invocationCallOrder: Array<number>;
  lastCall?: Parameters<T>;
  results: Array<MockFunctionResult<T>>;
}

type MockFunctionResult<T extends FunctionLike = UnknownFunction> =
  | MockFunctionResultIncomplete
  | MockFunctionResultReturn<T>
  | MockFunctionResultThrow;

type MockFunctionResultIncomplete = {
  type: 'incomplete';
  value: undefined;
};

type MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> = {
  type: 'return';
  value: ReturnType<T>;
};

type MockFunctionResultThrow = {
  type: 'throw';
  value: unknown;
};

// Note: ResolveType and RejectType are internal types used in MockInstance methods
// ResolveType<T> = ReturnType<T> extends PromiseLike<infer U> ? U : never
// RejectType<T> = ReturnType<T> extends PromiseLike<any> ? unknown : never