0
# Jest Mock
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: jest-mock
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install jest-mock`
10
11
## Core Imports
12
13
```typescript
14
import { fn, spyOn, mocked, replaceProperty, ModuleMocker } from "jest-mock";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { fn, spyOn, mocked, replaceProperty, ModuleMocker } = require("jest-mock");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { fn, spyOn, replaceProperty } from "jest-mock";
27
28
// Create a mock function
29
const mockFn = fn((x: number) => x * 2);
30
mockFn(5); // Returns 10
31
console.log(mockFn.mock.calls); // [[5]]
32
33
// Spy on an object method
34
const obj = { calculate: (a: number, b: number) => a + b };
35
const spy = spyOn(obj, 'calculate');
36
obj.calculate(2, 3); // Returns 5
37
console.log(spy.mock.calls); // [[2, 3]]
38
39
// Replace a property temporarily
40
const config = { apiUrl: 'https://api.example.com' };
41
const replaced = replaceProperty(config, 'apiUrl', 'https://test.example.com');
42
console.log(config.apiUrl); // 'https://test.example.com'
43
replaced.restore();
44
console.log(config.apiUrl); // 'https://api.example.com'
45
```
46
47
## Architecture
48
49
Jest Mock is built around several key components:
50
51
- **Mock Functions**: Core mock function implementation with call tracking and behavior control
52
- **Spy System**: Non-invasive observation and replacement of existing methods and properties
53
- **Metadata System**: Recursive object analysis for generating mocks from existing objects
54
- **ModuleMocker Class**: Low-level API for advanced mocking scenarios and custom mock generation
55
- **Type System**: Full TypeScript support with generic type preservation and utility types
56
57
## Capabilities
58
59
### Mock Function Creation
60
61
Creates standalone mock functions with comprehensive call tracking, return value control, and implementation management.
62
63
```typescript { .api }
64
function fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;
65
66
interface Mock<T extends FunctionLike = UnknownFunction> extends Function, MockInstance<T> {
67
new (...args: Parameters<T>): ReturnType<T>;
68
(...args: Parameters<T>): ReturnType<T>;
69
}
70
71
type FunctionLike = (...args: any) => any;
72
type UnknownFunction = (...args: Array<unknown>) => unknown;
73
```
74
75
[Mock Functions](./mock-functions.md)
76
77
### Spy Operations
78
79
Non-invasive spying and replacement of object methods and properties with automatic restoration capabilities.
80
81
```typescript { .api }
82
function spyOn<T extends object, K extends keyof T>(
83
object: T,
84
methodKey: K,
85
accessType?: 'get' | 'set'
86
): MockInstance;
87
88
function replaceProperty<T extends object, K extends keyof T>(
89
object: T,
90
propertyKey: K,
91
value: T[K]
92
): Replaced<T[K]>;
93
94
interface Replaced<T = unknown> {
95
restore(): void;
96
replaceValue(value: T): this;
97
}
98
```
99
100
[Spy Operations](./spy-operations.md)
101
102
### Type System and Utilities
103
104
Comprehensive TypeScript utilities for type-safe mocking with generic preservation and utility functions.
105
106
```typescript { .api }
107
function mocked<T extends object>(source: T, options?: {shallow?: boolean}): Mocked<T> | MockedShallow<T>;
108
109
type Mocked<T> = T extends ClassLike
110
? MockedClass<T>
111
: T extends FunctionLike
112
? MockedFunction<T>
113
: T extends object
114
? MockedObject<T>
115
: T;
116
117
type ClassLike = new (...args: any) => any;
118
```
119
120
[Type System](./type-system.md)
121
122
### Advanced Mock Generation
123
124
Low-level ModuleMocker class for metadata-driven mock generation and advanced mocking scenarios.
125
126
```typescript { .api }
127
class ModuleMocker {
128
constructor(global: typeof globalThis);
129
generateFromMetadata<T>(metadata: MockMetadata<T>): Mocked<T>;
130
getMetadata<T>(component: T, _refs?: Map<T, number>): MockMetadata<T> | null;
131
fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;
132
spyOn<T extends object, K extends keyof T>(object: T, methodKey: K, accessType?: 'get' | 'set'): MockInstance;
133
replaceProperty<T extends object, K extends keyof T>(object: T, propertyKey: K, value: T[K]): Replaced<T[K]>;
134
clearAllMocks(): void;
135
resetAllMocks(): void;
136
restoreAllMocks(): void;
137
isMockFunction(fn: unknown): fn is Mock<UnknownFunction>;
138
mocked<T extends object>(source: T, options?: {shallow?: boolean}): Mocked<T> | MockedShallow<T>;
139
}
140
```
141
142
[Advanced Mock Generation](./advanced-mock-generation.md)
143
144
## Global Types
145
146
```typescript { .api }
147
type MockMetadataType = 'object' | 'array' | 'regexp' | 'function' | 'constant' | 'collection' | 'null' | 'undefined';
148
149
interface MockMetadata<T, MetadataType = MockMetadataType> {
150
ref?: number;
151
members?: Record<string, MockMetadata<T>>;
152
mockImpl?: T;
153
name?: string;
154
refID?: number;
155
type?: MetadataType;
156
value?: T;
157
length?: number;
158
}
159
160
interface MockInstance<T extends FunctionLike = UnknownFunction> extends Disposable {
161
_isMockFunction: true;
162
_protoImpl: Function;
163
mock: MockFunctionState<T>;
164
getMockImplementation(): T | undefined;
165
getMockName(): string;
166
mockClear(): this;
167
mockReset(): this;
168
mockRestore(): void;
169
mockImplementation(fn: T): this;
170
mockImplementationOnce(fn: T): this;
171
withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>;
172
withImplementation(fn: T, callback: () => void): void;
173
mockName(name: string): this;
174
mockReturnThis(): this;
175
mockReturnValue(value: ReturnType<T>): this;
176
mockReturnValueOnce(value: ReturnType<T>): this;
177
mockResolvedValue<U>(value: U): this; // where ReturnType<T> extends PromiseLike<U>
178
mockResolvedValueOnce<U>(value: U): this; // where ReturnType<T> extends PromiseLike<U>
179
mockRejectedValue(value: unknown): this; // for Promise-returning functions
180
mockRejectedValueOnce(value: unknown): this; // for Promise-returning functions
181
}
182
183
interface MockFunctionState<T extends FunctionLike = UnknownFunction> {
184
calls: Array<Parameters<T>>;
185
instances: Array<ReturnType<T>>;
186
contexts: Array<ThisParameterType<T>>;
187
invocationCallOrder: Array<number>;
188
lastCall?: Parameters<T>;
189
results: Array<MockFunctionResult<T>>;
190
}
191
192
type MockFunctionResult<T extends FunctionLike = UnknownFunction> =
193
| MockFunctionResultIncomplete
194
| MockFunctionResultReturn<T>
195
| MockFunctionResultThrow;
196
197
type MockFunctionResultIncomplete = {
198
type: 'incomplete';
199
value: undefined;
200
};
201
202
type MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> = {
203
type: 'return';
204
value: ReturnType<T>;
205
};
206
207
type MockFunctionResultThrow = {
208
type: 'throw';
209
value: unknown;
210
};
211
212
// Note: ResolveType and RejectType are internal types used in MockInstance methods
213
// ResolveType<T> = ReturnType<T> extends PromiseLike<infer U> ? U : never
214
// RejectType<T> = ReturnType<T> extends PromiseLike<any> ? unknown : never
215
```