Mock mate library for mocking functions, HTTP requests, and file system operations in Node.js testing
npx @tessl/cli install tessl/npm-mm@4.0.00
# mm (Mock Mate)
1
2
mm is a flexible and comprehensive mocking library for Node.js testing environments. It provides extensive capabilities for mocking functions, HTTP/HTTPS requests, child processes, and class methods with built-in spy functionality and automatic call tracking.
3
4
## Package Information
5
6
- **Package Name**: mm
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install mm --save-dev`
10
11
## Core Imports
12
13
ESM:
14
15
```typescript
16
// Default import (proxy function)
17
import mm from "mm";
18
19
// Named imports
20
import { mock, restore, spy, data, error, mm as mmNamed } from "mm";
21
22
// Mixed imports
23
import mm, { restore, spy } from "mm";
24
25
// Namespace imports
26
import * as mockMate from "mm";
27
```
28
29
CommonJS:
30
31
```javascript
32
// Default import
33
const mm = require("mm");
34
35
// Named imports
36
const { mock, restore, spy, data, error, mm: mmNamed } = require("mm");
37
38
// Mixed imports
39
const mm = require("mm");
40
const { restore, spy } = require("mm");
41
```
42
43
## Basic Usage
44
45
```typescript
46
import fs from "node:fs";
47
import mm from "mm";
48
49
// Mock a function to return specific data
50
mm.data(fs, "readFileSync", "mocked file content");
51
console.log(fs.readFileSync("any-file.txt")); // => "mocked file content"
52
53
// Mock a function to throw an error
54
mm.error(fs, "readFile", "Mock error message");
55
56
// Spy on a function (track calls without changing behavior)
57
const obj = { calculate: (a, b) => a + b };
58
mm.spy(obj, "calculate");
59
obj.calculate(2, 3); // Returns 5, but also tracks the call
60
console.log(obj.calculate.called); // => 1
61
console.log(obj.calculate.lastCalledArguments); // => [2, 3]
62
63
// Restore all mocks
64
mm.restore();
65
```
66
67
## Architecture
68
69
mm is built around several key components:
70
71
- **Core Mocking Engine**: Proxy-based function replacement with automatic spy instrumentation
72
- **Async/Sync Support**: Handles callbacks, promises, generators, and synchronous functions
73
- **HTTP Request Mocking**: Complete HTTP/HTTPS request and response simulation
74
- **Call Tracking**: Built-in spy functionality with detailed call history
75
- **Resource Management**: Modern JavaScript features like Symbol.asyncDispose support
76
- **Restoration System**: Clean teardown of all mocks and spies
77
78
## Capabilities
79
80
### Core Function Mocking
81
82
Basic mocking functionality for replacing function behavior with custom implementations, error simulation, or data returns.
83
84
```typescript { .api }
85
// Default export - proxy function (can be called directly)
86
function mm(target: any, property: PropertyKey, value?: any): void;
87
88
// Named export - explicit mock function
89
function mock(target: any, property: PropertyKey, value?: any): void;
90
91
// Alternative access patterns (all equivalent)
92
mm.mock(target: any, property: PropertyKey, value?: any): void;
93
mm.mm(target: any, property: PropertyKey, value?: any): void;
94
95
// Check if a property is mocked
96
function isMocked(target: any, property: PropertyKey): boolean;
97
98
// Restore all mocks
99
function restore(): void;
100
```
101
102
[Core Mocking](./core-mocking.md)
103
104
### Asynchronous Function Mocking
105
106
Comprehensive mocking for async functions, callbacks, promises, and generators with timeout and error simulation support.
107
108
```typescript { .api }
109
// Mock async function to return data (with alias)
110
function mockData(mod: any, method: string | symbol, data: any, timeout?: number): void;
111
function data(mod: any, method: string | symbol, data: any, timeout?: number): void; // alias
112
113
// Mock async function to return multiple data arguments (with alias)
114
function mockDatas(mod: any, method: string | symbol, datas: any[] | any, timeout?: number): void;
115
function datas(mod: any, method: string | symbol, datas: any[] | any, timeout?: number): void; // alias
116
117
// Mock async function to return empty response (with alias)
118
function mockEmpty(mod: any, method: string | symbol, timeout?: number): void;
119
function empty(mod: any, method: string | symbol, timeout?: number): void; // alias
120
121
// Mock async function to return error (with alias)
122
function mockError(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;
123
function error(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void; // alias
124
125
// Mock async function to return error once
126
function errorOnce(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;
127
128
// Mock with Symbol.asyncDispose support
129
function dataWithAsyncDispose(mod: any, method: string | symbol, data: any, timeout?: number): void;
130
```
131
132
[Async Mocking](./async-mocking.md)
133
134
### Synchronous Function Mocking
135
136
Direct mocking for synchronous functions with immediate return values or error throwing.
137
138
```typescript { .api }
139
// Mock sync function to return data
140
function syncData(mod: any, method: string | symbol, data?: any): void;
141
142
// Mock sync function to throw error
143
function syncError(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any>): void;
144
```
145
146
[Sync Mocking](./sync-mocking.md)
147
148
### HTTP Request Mocking
149
150
Mock HTTP and HTTPS requests with custom responses, headers, and error simulation for testing network-dependent code.
151
152
```typescript { .api }
153
// Direct function imports
154
function mockHttpRequest(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
155
function mockHttpsRequest(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
156
function mockHttpRequestError(url: RequestURL, reqError?: MockError, resError?: MockError, delay?: number): void;
157
function mockHttpsRequestError(url: RequestURL, reqError?: MockError, resError?: MockError, delay?: number): void;
158
159
// Namespace access patterns
160
mm.http.request(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
161
mm.http.requestError(url: RequestURL, reqError?: MockError, resError?: MockError, delay?: number): void;
162
mm.https.request(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
163
mm.https.requestError(url: RequestURL, reqError?: MockError, resError?: MockError, delay?: number): void;
164
165
// Named export access
166
http.request(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
167
https.request(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
168
169
type RequestURL = string | RegExp | URL | object;
170
type ResponseData = string | Buffer | Readable;
171
```
172
173
[HTTP Mocking](./http-mocking.md)
174
175
### Spy Functionality
176
177
Track function calls without changing their behavior, including call counts and argument history.
178
179
```typescript { .api }
180
// Create a spy that tracks calls without changing behavior
181
function spy(mod: any, method: string | symbol): void;
182
183
// Mock class methods affecting all instances
184
function classMethod(instance: any, property: PropertyKey, value?: any): void;
185
```
186
187
When functions are mocked, they automatically gain spy properties:
188
189
```typescript { .api }
190
interface SpyProperties {
191
called: number; // Number of times called
192
calledArguments: any[][]; // All call arguments
193
lastCalledArguments: any[]; // Most recent call arguments
194
}
195
```
196
197
[Spy Functions](./spy-functions.md)
198
199
### Process and System Mocking
200
201
Mock child processes and system operations for testing command-line interactions and process spawning.
202
203
```typescript { .api }
204
// Mock child_process.spawn
205
function spawn(code: number, stdout: string, stderr: string, timeout?: number): void;
206
```
207
208
[System Mocking](./system-mocking.md)
209
210
## Types
211
212
```typescript { .api }
213
// Error types for mocking
214
type MockError = Error | string;
215
216
// HTTP mocking types
217
type RequestURL = string | RegExp | URL | object;
218
type ResponseData = string | Buffer | Readable;
219
220
// Property key types for mocking
221
type PropertyKey = string | number | symbol;
222
223
// Spy properties automatically added to mocked functions
224
interface SpyProperties {
225
called: number;
226
calledArguments: any[][];
227
lastCalledArguments: any[];
228
}
229
230
// HTTP namespace interfaces
231
interface HttpMockNamespace {
232
request: typeof mockHttpRequest;
233
requestError: typeof mockHttpRequestError;
234
}
235
236
interface HttpsMockNamespace {
237
request: typeof mockHttpsRequest;
238
requestError: typeof mockHttpsRequestError;
239
}
240
241
// Main mm object interface (default export)
242
interface MmInstance {
243
// Callable as function
244
(target: any, property: PropertyKey, value?: any): void;
245
246
// Core methods
247
mock: typeof mock;
248
mm: typeof mock;
249
isMocked: typeof isMocked;
250
restore: typeof restore;
251
252
// Async methods
253
data: typeof mockData;
254
mockData: typeof mockData;
255
datas: typeof mockDatas;
256
mockDatas: typeof mockDatas;
257
empty: typeof mockEmpty;
258
mockEmpty: typeof mockEmpty;
259
error: typeof mockError;
260
mockError: typeof mockError;
261
errorOnce: typeof errorOnce;
262
dataWithAsyncDispose: typeof dataWithAsyncDispose;
263
264
// Sync methods
265
syncData: typeof syncData;
266
syncEmpty: typeof syncEmpty;
267
syncError: typeof syncError;
268
269
// Spy methods
270
spy: typeof spy;
271
classMethod: typeof classMethod;
272
273
// HTTP namespaces
274
http: HttpMockNamespace;
275
https: HttpsMockNamespace;
276
277
// System methods
278
spawn: typeof spawn;
279
}
280
```
281
282
## Error Handling
283
284
mm provides several error simulation patterns:
285
286
- **Async errors**: Via callback with `mockError()` and `errorOnce()`
287
- **Sync errors**: Immediate throwing with `syncError()`
288
- **HTTP errors**: Request/response error simulation with `http.requestError()` and `https.requestError()`
289
- **Custom error properties**: Additional error metadata via props parameter