0
# Mock Functions
1
2
Core mock function creation and control capabilities for creating standalone mock functions with comprehensive call tracking and behavior management.
3
4
## Capabilities
5
6
### Mock Function Creation
7
8
Creates a new mock function with optional implementation.
9
10
```typescript { .api }
11
/**
12
* Creates a mock function with optional implementation
13
* @param implementation - Optional function implementation
14
* @returns Mock function with tracking and control methods
15
*/
16
function fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;
17
18
interface Mock<T extends FunctionLike = UnknownFunction> extends Function, MockInstance<T> {
19
new (...args: Parameters<T>): ReturnType<T>;
20
(...args: Parameters<T>): ReturnType<T>;
21
}
22
23
type FunctionLike = (...args: any) => any;
24
type UnknownFunction = (...args: Array<unknown>) => unknown;
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import { fn } from "jest-mock";
31
32
// Create a mock function without implementation
33
const mockFn = fn();
34
mockFn('hello', 42);
35
console.log(mockFn.mock.calls); // [['hello', 42]]
36
37
// Create a mock function with implementation
38
const addMock = fn((a: number, b: number) => a + b);
39
console.log(addMock(2, 3)); // 5
40
console.log(addMock.mock.calls); // [[2, 3]]
41
42
// Mock a constructor
43
const MockClass = fn();
44
const instance = new MockClass('arg1', 'arg2');
45
console.log(MockClass.mock.instances); // [instance]
46
console.log(MockClass.mock.calls); // [['arg1', 'arg2']]
47
```
48
49
### Implementation Control
50
51
Control mock function behavior with custom implementations.
52
53
```typescript { .api }
54
/**
55
* Sets the default implementation for the mock function
56
* @param fn - Function implementation
57
* @returns Mock instance for chaining
58
*/
59
mockImplementation(fn: T): this;
60
61
/**
62
* Sets a one-time implementation for the next call
63
* @param fn - Function implementation for next call only
64
* @returns Mock instance for chaining
65
*/
66
mockImplementationOnce(fn: T): this;
67
68
/**
69
* Temporarily overrides implementation within callback
70
* @param fn - Temporary implementation
71
* @param callback - Function to execute with temporary implementation
72
* @returns Promise if callback is async, void otherwise
73
*/
74
withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>;
75
withImplementation(fn: T, callback: () => void): void;
76
```
77
78
**Usage Examples:**
79
80
```typescript
81
import { fn } from "jest-mock";
82
83
const mockFn = fn();
84
85
// Set default implementation
86
mockFn.mockImplementation((x: number) => x * 2);
87
console.log(mockFn(5)); // 10
88
89
// One-time implementations
90
mockFn.mockImplementationOnce((x: number) => x + 1);
91
console.log(mockFn(5)); // 6 (one-time)
92
console.log(mockFn(5)); // 10 (back to default)
93
94
// Temporary implementation
95
mockFn.withImplementation((x: number) => x - 1, () => {
96
console.log(mockFn(5)); // 4
97
});
98
console.log(mockFn(5)); // 10 (restored)
99
```
100
101
### Return Value Control
102
103
Control return values without full implementation replacement.
104
105
```typescript { .api }
106
/**
107
* Sets the default return value for the mock function
108
* @param value - Default return value
109
* @returns Mock instance for chaining
110
*/
111
mockReturnValue(value: ReturnType<T>): this;
112
113
/**
114
* Sets a one-time return value for the next call
115
* @param value - Return value for next call only
116
* @returns Mock instance for chaining
117
*/
118
mockReturnValueOnce(value: ReturnType<T>): this;
119
120
/**
121
* Makes the mock function return 'this'
122
* @returns Mock instance for chaining
123
*/
124
mockReturnThis(): this;
125
```
126
127
**Usage Examples:**
128
129
```typescript
130
import { fn } from "jest-mock";
131
132
const mockFn = fn();
133
134
// Set default return value
135
mockFn.mockReturnValue(42);
136
console.log(mockFn()); // 42
137
138
// One-time return values
139
mockFn.mockReturnValueOnce(100);
140
console.log(mockFn()); // 100 (one-time)
141
console.log(mockFn()); // 42 (back to default)
142
143
// Return this for chaining
144
const chainable = fn();
145
chainable.mockReturnThis();
146
console.log(chainable() === chainable); // true
147
```
148
149
### Promise Control
150
151
Special handling for async functions and promises.
152
153
```typescript { .api }
154
/**
155
* Sets the default resolved value for promise-returning mocks
156
* @param value - Value to resolve with
157
* @returns Mock instance for chaining
158
*/
159
mockResolvedValue(value: ResolveType<T>): this;
160
161
/**
162
* Sets a one-time resolved value for the next call
163
* @param value - Value to resolve with for next call only
164
* @returns Mock instance for chaining
165
*/
166
mockResolvedValueOnce(value: ResolveType<T>): this;
167
168
/**
169
* Sets the default rejected value for promise-returning mocks
170
* @param value - Value to reject with
171
* @returns Mock instance for chaining
172
*/
173
mockRejectedValue(value: RejectType<T>): this;
174
175
/**
176
* Sets a one-time rejected value for the next call
177
* @param value - Value to reject with for next call only
178
* @returns Mock instance for chaining
179
*/
180
mockRejectedValueOnce(value: RejectType<T>): this;
181
182
type ResolveType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<infer U> ? U : never;
183
type RejectType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<any> ? unknown : never;
184
```
185
186
**Usage Examples:**
187
188
```typescript
189
import { fn } from "jest-mock";
190
191
const asyncMock = fn();
192
193
// Mock resolved values
194
asyncMock.mockResolvedValue('success');
195
const result = await asyncMock();
196
console.log(result); // 'success'
197
198
// One-time resolved value
199
asyncMock.mockResolvedValueOnce('once');
200
console.log(await asyncMock()); // 'once'
201
console.log(await asyncMock()); // 'success'
202
203
// Mock rejected values
204
asyncMock.mockRejectedValue(new Error('failed'));
205
try {
206
await asyncMock();
207
} catch (error) {
208
console.log(error.message); // 'failed'
209
}
210
```
211
212
### Mock State Management
213
214
Control and inspect mock function state.
215
216
```typescript { .api }
217
/**
218
* Clears call history but preserves implementation
219
* @returns Mock instance for chaining
220
*/
221
mockClear(): this;
222
223
/**
224
* Resets mock to default state (clears calls and implementation)
225
* @returns Mock instance for chaining
226
*/
227
mockReset(): this;
228
229
/**
230
* Restores original implementation (for spies)
231
*/
232
mockRestore(): void;
233
234
/**
235
* Sets a custom name for the mock function
236
* @param name - Name for the mock function
237
* @returns Mock instance for chaining
238
*/
239
mockName(name: string): this;
240
241
/**
242
* Gets the current name of the mock function
243
* @returns Current mock name or default
244
*/
245
getMockName(): string;
246
247
/**
248
* Gets the current implementation of the mock function
249
* @returns Current implementation or undefined
250
*/
251
getMockImplementation(): T | undefined;
252
```
253
254
**Usage Examples:**
255
256
```typescript
257
import { fn } from "jest-mock";
258
259
const mockFn = fn((x: number) => x * 2);
260
mockFn.mockName('multiplier');
261
262
mockFn(5);
263
mockFn(10);
264
265
console.log(mockFn.getMockName()); // 'multiplier'
266
console.log(mockFn.mock.calls.length); // 2
267
268
// Clear call history only
269
mockFn.mockClear();
270
console.log(mockFn.mock.calls.length); // 0
271
console.log(mockFn(3)); // 6 (implementation preserved)
272
273
// Reset everything
274
mockFn.mockReset();
275
console.log(mockFn(3)); // undefined (implementation cleared)
276
```
277
278
## Types
279
280
```typescript { .api }
281
interface MockFunctionState<T extends FunctionLike = UnknownFunction> {
282
/** All call arguments made to the mock function */
283
calls: Array<Parameters<T>>;
284
/** All instances created when mock is called as constructor */
285
instances: Array<ReturnType<T>>;
286
/** All function contexts (this values) for each call */
287
contexts: Array<ThisParameterType<T>>;
288
/** Order of invocation relative to all mocks in test */
289
invocationCallOrder: Array<number>;
290
/** Arguments from the most recent call */
291
lastCall?: Parameters<T>;
292
/** Results from all calls (return values or thrown errors) */
293
results: Array<MockFunctionResult<T>>;
294
}
295
296
type MockFunctionResult<T extends FunctionLike = UnknownFunction> =
297
| MockFunctionResultIncomplete
298
| MockFunctionResultReturn<T>
299
| MockFunctionResultThrow;
300
301
type MockFunctionResultIncomplete = {
302
type: 'incomplete';
303
value: undefined;
304
};
305
306
type MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> = {
307
type: 'return';
308
value: ReturnType<T>;
309
};
310
311
type MockFunctionResultThrow = {
312
type: 'throw';
313
value: unknown;
314
};
315
```