0
# Asynchronous Function Mocking
1
2
Comprehensive mocking capabilities for asynchronous functions including callback-based functions, promises, async/await, and generator functions. All async mocks support timeout simulation and automatic spy tracking.
3
4
## Capabilities
5
6
### Mock Data Return
7
8
Mock asynchronous functions to return specific data via callback or promise resolution.
9
10
```typescript { .api }
11
/**
12
* Mock async function to return data via callback(null, data) or promise resolution
13
* @param mod - Object containing the method to mock
14
* @param method - Method name to mock
15
* @param data - Data to return
16
* @param timeout - Optional delay in milliseconds (default: 0)
17
*/
18
function mockData(mod: any, method: string | symbol, data: any, timeout?: number): void;
19
20
// Alias available
21
function data(mod: any, method: string | symbol, data: any, timeout?: number): void;
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import fs from "node:fs";
28
import { mockData } from "mm";
29
30
// Mock callback-based function
31
mockData(fs, "readFile", "mocked file content");
32
fs.readFile("file.txt", "utf8", (err, data) => {
33
console.log(err); // => null
34
console.log(data); // => "mocked file content"
35
});
36
37
// Mock async function with timeout
38
const api = {
39
fetchUser: async (id: string) => ({ id, name: "Real User" })
40
};
41
mockData(api, "fetchUser", { id: "123", name: "Mock User" }, 100);
42
const user = await api.fetchUser("123"); // Resolves after 100ms
43
```
44
45
### Mock Multiple Data Arguments
46
47
Mock asynchronous functions to return multiple arguments via callback or promise.
48
49
```typescript { .api }
50
/**
51
* Mock async function to return multiple data arguments via callback(null, ...datas)
52
* @param mod - Object containing the method to mock
53
* @param method - Method name to mock
54
* @param datas - Array of data arguments to return, or single value
55
* @param timeout - Optional delay in milliseconds (default: 0)
56
*/
57
function mockDatas(mod: any, method: string | symbol, datas: any[] | any, timeout?: number): void;
58
59
// Alias available
60
function datas(mod: any, method: string | symbol, datas: any[] | any, timeout?: number): void;
61
```
62
63
**Usage Examples:**
64
65
```typescript
66
import { mockDatas } from "mm";
67
68
// Mock with multiple return values
69
const urllib = {
70
request: (url: string, callback: (err: any, data: Buffer, headers: any) => void) => {}
71
};
72
73
mockDatas(urllib, "request", [Buffer.from("response data"), { "content-type": "text/plain" }]);
74
urllib.request("http://example.com", (err, data, headers) => {
75
console.log(err); // => null
76
console.log(data); // => Buffer("response data")
77
console.log(headers); // => { "content-type": "text/plain" }
78
});
79
80
// Single value (automatically wrapped in array for callbacks)
81
mockDatas(urllib, "request", Buffer.from("simple response"));
82
```
83
84
### Mock Empty Response
85
86
Mock asynchronous functions to return callback(null, null) or resolve with undefined.
87
88
```typescript { .api }
89
/**
90
* Mock async function to return empty response via callback(null, null)
91
* @param mod - Object containing the method to mock
92
* @param method - Method name to mock
93
* @param timeout - Optional delay in milliseconds (default: 0)
94
*/
95
function mockEmpty(mod: any, method: string | symbol, timeout?: number): void;
96
97
// Alias available
98
function empty(mod: any, method: string | symbol, timeout?: number): void;
99
```
100
101
**Usage Examples:**
102
103
```typescript
104
import { mockEmpty } from "mm";
105
106
const mysql = {
107
query: (sql: string, callback: (err: any, results?: any) => void) => {}
108
};
109
110
mockEmpty(mysql, "query");
111
mysql.query("DELETE FROM users", (err, results) => {
112
console.log(err); // => null
113
console.log(results); // => null
114
});
115
```
116
117
### Mock Errors
118
119
Mock asynchronous functions to return errors via callback or promise rejection.
120
121
```typescript { .api }
122
/**
123
* Mock async function to return error via callback or promise rejection
124
* @param mod - Object containing the method to mock
125
* @param method - Method name to mock
126
* @param error - Error message string or Error instance (optional)
127
* @param props - Additional error properties or timeout if number (optional)
128
* @param timeout - Delay in milliseconds (optional)
129
*/
130
function mockError(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;
131
132
// Alias available
133
function error(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;
134
135
type MockError = Error | string;
136
```
137
138
**Usage Examples:**
139
140
```typescript
141
import fs from "node:fs";
142
import { mockError } from "mm";
143
144
// Mock with simple error message
145
mockError(fs, "readFile", "File not found");
146
fs.readFile("missing.txt", (err, data) => {
147
console.log(err.message); // => "File not found"
148
console.log(err.name); // => "MockError"
149
});
150
151
// Mock with Error instance and custom properties
152
const customError = new Error("Permission denied");
153
mockError(fs, "readFile", customError, { code: "EACCES", errno: -13 });
154
155
// Mock with timeout (third parameter as number)
156
mockError(fs, "readFile", "Timeout error", 1000); // Error after 1 second
157
```
158
159
### Mock Errors Once
160
161
Mock asynchronous functions to return an error once, then automatically restore the original behavior.
162
163
```typescript { .api }
164
/**
165
* Mock async function to return error once, then restore original behavior
166
* @param mod - Object containing the method to mock
167
* @param method - Method name to mock
168
* @param error - Error message string or Error instance (optional)
169
* @param props - Additional error properties or timeout if number (optional)
170
* @param timeout - Delay in milliseconds (optional)
171
*/
172
function errorOnce(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;
173
```
174
175
**Usage Examples:**
176
177
```typescript
178
import fs from "node:fs";
179
import { errorOnce } from "mm";
180
181
errorOnce(fs, "readFile", "Temporary failure");
182
183
// First call returns error
184
fs.readFile("file.txt", (err, data) => {
185
console.log(err.message); // => "Temporary failure"
186
});
187
188
// Second call uses original function (no longer mocked)
189
fs.readFile("file.txt", (err, data) => {
190
// Real file system behavior
191
});
192
```
193
194
### Mock with AsyncDispose Support
195
196
Mock data with Symbol.asyncDispose support for modern JavaScript resource management patterns.
197
198
```typescript { .api }
199
/**
200
* Mock data with Symbol.asyncDispose support for resource management
201
* @param mod - Object containing the method to mock
202
* @param method - Method name to mock
203
* @param data - Data to return (will be enhanced with asyncDispose)
204
* @param timeout - Optional delay in milliseconds (default: 0)
205
*/
206
function dataWithAsyncDispose(mod: any, method: string | symbol, data: any, timeout?: number): void;
207
```
208
209
**Usage Examples:**
210
211
```typescript
212
import { dataWithAsyncDispose } from "mm";
213
214
const locker = {
215
tryLock: async (key: string) => ({ locked: false })
216
};
217
218
dataWithAsyncDispose(locker, "tryLock", { locked: true });
219
220
// Use with await using for automatic resource cleanup
221
await using lock = await locker.tryLock("resource-key");
222
console.log(lock.locked); // => true
223
// lock automatically disposed when leaving scope
224
```
225
226
## Function Type Support
227
228
mm handles different asynchronous function patterns automatically:
229
230
### Callback Functions
231
232
Traditional Node.js callback pattern with `(err, ...results)`:
233
234
```typescript
235
import { mockData } from "mm";
236
237
const fs = require("fs");
238
mockData(fs, "readFile", "mock content");
239
240
fs.readFile("file.txt", "utf8", (err, data) => {
241
// err = null, data = "mock content"
242
});
243
```
244
245
### Promise/Async Functions
246
247
Modern promise-based and async/await functions:
248
249
```typescript
250
import { mockData } from "mm";
251
252
const api = {
253
fetchData: async () => "real data"
254
};
255
256
mockData(api, "fetchData", "mock data");
257
const result = await api.fetchData(); // => "mock data"
258
```
259
260
### Generator Functions
261
262
ES6 generator functions with yield support:
263
264
```typescript
265
import { mockData } from "mm";
266
267
const service = {
268
*processData() {
269
yield "real processing";
270
return "real result";
271
}
272
};
273
274
mockData(service, "processData", "mock result");
275
const gen = service.processData();
276
const result = gen.next().value; // => "mock result"
277
```
278
279
## Timeout and Delay
280
281
All async mocking functions support optional timeout parameters to simulate real-world delays:
282
283
```typescript
284
// Simulate slow network request
285
mockData(api, "slowRequest", "delayed response", 2000); // 2 second delay
286
287
// Simulate timeout error
288
mockError(api, "unreliableService", "Timeout", 5000); // Error after 5 seconds
289
```
290
291
## Types
292
293
```typescript { .api }
294
// Error types for async mocking
295
type MockError = Error | string;
296
297
// Spy properties added to all mocked functions
298
interface SpyProperties {
299
called: number;
300
calledArguments: any[][];
301
lastCalledArguments: any[];
302
}
303
```