CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest-mock

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

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

mock-functions.mddocs/

Mock Functions

Core mock function creation and control capabilities for creating standalone mock functions with comprehensive call tracking and behavior management.

Capabilities

Mock Function Creation

Creates a new mock function with optional implementation.

/**
 * Creates a mock function with optional implementation
 * @param implementation - Optional function implementation
 * @returns Mock function with tracking and control methods
 */
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;

Usage Examples:

import { fn } from "jest-mock";

// Create a mock function without implementation
const mockFn = fn();
mockFn('hello', 42);
console.log(mockFn.mock.calls); // [['hello', 42]]

// Create a mock function with implementation  
const addMock = fn((a: number, b: number) => a + b);
console.log(addMock(2, 3)); // 5
console.log(addMock.mock.calls); // [[2, 3]]

// Mock a constructor
const MockClass = fn();
const instance = new MockClass('arg1', 'arg2');
console.log(MockClass.mock.instances); // [instance]
console.log(MockClass.mock.calls); // [['arg1', 'arg2']]

Implementation Control

Control mock function behavior with custom implementations.

/**
 * Sets the default implementation for the mock function
 * @param fn - Function implementation
 * @returns Mock instance for chaining
 */
mockImplementation(fn: T): this;

/**
 * Sets a one-time implementation for the next call
 * @param fn - Function implementation for next call only
 * @returns Mock instance for chaining
 */
mockImplementationOnce(fn: T): this;

/**
 * Temporarily overrides implementation within callback
 * @param fn - Temporary implementation
 * @param callback - Function to execute with temporary implementation
 * @returns Promise if callback is async, void otherwise
 */
withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>;
withImplementation(fn: T, callback: () => void): void;

Usage Examples:

import { fn } from "jest-mock";

const mockFn = fn();

// Set default implementation
mockFn.mockImplementation((x: number) => x * 2);
console.log(mockFn(5)); // 10

// One-time implementations
mockFn.mockImplementationOnce((x: number) => x + 1);
console.log(mockFn(5)); // 6 (one-time)
console.log(mockFn(5)); // 10 (back to default)

// Temporary implementation
mockFn.withImplementation((x: number) => x - 1, () => {
  console.log(mockFn(5)); // 4
});
console.log(mockFn(5)); // 10 (restored)

Return Value Control

Control return values without full implementation replacement.

/**
 * Sets the default return value for the mock function
 * @param value - Default return value
 * @returns Mock instance for chaining
 */
mockReturnValue(value: ReturnType<T>): this;

/**
 * Sets a one-time return value for the next call
 * @param value - Return value for next call only
 * @returns Mock instance for chaining
 */
mockReturnValueOnce(value: ReturnType<T>): this;

/**
 * Makes the mock function return 'this'
 * @returns Mock instance for chaining
 */
mockReturnThis(): this;

Usage Examples:

import { fn } from "jest-mock";

const mockFn = fn();

// Set default return value
mockFn.mockReturnValue(42);
console.log(mockFn()); // 42

// One-time return values
mockFn.mockReturnValueOnce(100);
console.log(mockFn()); // 100 (one-time)
console.log(mockFn()); // 42 (back to default)

// Return this for chaining
const chainable = fn();
chainable.mockReturnThis();
console.log(chainable() === chainable); // true

Promise Control

Special handling for async functions and promises.

/**
 * Sets the default resolved value for promise-returning mocks
 * @param value - Value to resolve with
 * @returns Mock instance for chaining
 */
mockResolvedValue(value: ResolveType<T>): this;

/**
 * Sets a one-time resolved value for the next call
 * @param value - Value to resolve with for next call only
 * @returns Mock instance for chaining
 */
mockResolvedValueOnce(value: ResolveType<T>): this;

/**
 * Sets the default rejected value for promise-returning mocks
 * @param value - Value to reject with
 * @returns Mock instance for chaining
 */
mockRejectedValue(value: RejectType<T>): this;

/**
 * Sets a one-time rejected value for the next call
 * @param value - Value to reject with for next call only
 * @returns Mock instance for chaining
 */
mockRejectedValueOnce(value: RejectType<T>): this;

type ResolveType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<infer U> ? U : never;
type RejectType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<any> ? unknown : never;

Usage Examples:

import { fn } from "jest-mock";

const asyncMock = fn();

// Mock resolved values
asyncMock.mockResolvedValue('success');
const result = await asyncMock();
console.log(result); // 'success'

// One-time resolved value
asyncMock.mockResolvedValueOnce('once');
console.log(await asyncMock()); // 'once'
console.log(await asyncMock()); // 'success'

// Mock rejected values
asyncMock.mockRejectedValue(new Error('failed'));
try {
  await asyncMock();
} catch (error) {
  console.log(error.message); // 'failed'
}

Mock State Management

Control and inspect mock function state.

/**
 * Clears call history but preserves implementation
 * @returns Mock instance for chaining
 */
mockClear(): this;

/**
 * Resets mock to default state (clears calls and implementation)
 * @returns Mock instance for chaining
 */
mockReset(): this;

/**
 * Restores original implementation (for spies)
 */
mockRestore(): void;

/**
 * Sets a custom name for the mock function
 * @param name - Name for the mock function
 * @returns Mock instance for chaining
 */
mockName(name: string): this;

/**
 * Gets the current name of the mock function
 * @returns Current mock name or default
 */
getMockName(): string;

/**
 * Gets the current implementation of the mock function
 * @returns Current implementation or undefined
 */
getMockImplementation(): T | undefined;

Usage Examples:

import { fn } from "jest-mock";

const mockFn = fn((x: number) => x * 2);
mockFn.mockName('multiplier');

mockFn(5);
mockFn(10);

console.log(mockFn.getMockName()); // 'multiplier'
console.log(mockFn.mock.calls.length); // 2

// Clear call history only
mockFn.mockClear();
console.log(mockFn.mock.calls.length); // 0
console.log(mockFn(3)); // 6 (implementation preserved)

// Reset everything
mockFn.mockReset();
console.log(mockFn(3)); // undefined (implementation cleared)

Types

interface MockFunctionState<T extends FunctionLike = UnknownFunction> {
  /** All call arguments made to the mock function */
  calls: Array<Parameters<T>>;
  /** All instances created when mock is called as constructor */
  instances: Array<ReturnType<T>>;
  /** All function contexts (this values) for each call */
  contexts: Array<ThisParameterType<T>>;
  /** Order of invocation relative to all mocks in test */
  invocationCallOrder: Array<number>;
  /** Arguments from the most recent call */
  lastCall?: Parameters<T>;
  /** Results from all calls (return values or thrown errors) */
  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;
};

docs

advanced-mock-generation.md

index.md

mock-functions.md

spy-operations.md

type-system.md

tile.json