0
# Synchronous Function Mocking
1
2
Direct mocking capabilities for synchronous functions with immediate return values or error throwing. Perfect for testing pure functions, synchronous APIs, and blocking operations.
3
4
## Capabilities
5
6
### Mock Synchronous Data Return
7
8
Mock synchronous functions to return specific data immediately.
9
10
```typescript { .api }
11
/**
12
* Mock synchronous function to return data immediately
13
* @param mod - Object containing the method to mock
14
* @param method - Method name to mock
15
* @param data - Data to return (optional, defaults to undefined)
16
*/
17
function syncData(mod: any, method: string | symbol, data?: any): void;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import fs from "node:fs";
24
import { syncData } from "mm";
25
26
// Mock with specific data
27
syncData(fs, "readFileSync", Buffer.from("mocked file content"));
28
const content = fs.readFileSync("any-file.txt");
29
console.log(content); // => Buffer("mocked file content")
30
31
// Mock with object data
32
const config = { get: (key: string) => "real value" };
33
syncData(config, "get", "mock value");
34
console.log(config.get("any-key")); // => "mock value"
35
36
// Mock with complex data structures
37
const parser = { parseXML: (xml: string) => ({ error: "real parsing" }) };
38
syncData(parser, "parseXML", { data: { users: [{ id: 1, name: "Mock User" }] } });
39
```
40
41
### Mock Synchronous Empty Return
42
43
Mock synchronous functions to return undefined immediately.
44
45
```typescript { .api }
46
/**
47
* Mock synchronous function to return undefined
48
* @param mod - Object containing the method to mock
49
* @param method - Method name to mock
50
*/
51
function syncEmpty(mod: any, method: string | symbol): void;
52
```
53
54
**Usage Examples:**
55
56
```typescript
57
import { syncEmpty } from "mm";
58
59
// Mock void functions
60
const logger = {
61
log: (message: string) => console.log(`[LOG] ${message}`)
62
};
63
64
syncEmpty(logger, "log");
65
logger.log("This won't be printed"); // Returns undefined, no output
66
67
// Mock functions that should do nothing
68
const cache = {
69
clear: () => { /* complex clearing logic */ }
70
};
71
72
syncEmpty(cache, "clear");
73
cache.clear(); // Does nothing, returns undefined
74
```
75
76
### Mock Synchronous Errors
77
78
Mock synchronous functions to throw errors immediately.
79
80
```typescript { .api }
81
/**
82
* Mock synchronous function to throw error immediately
83
* @param mod - Object containing the method to mock
84
* @param method - Method name to mock
85
* @param error - Error message string or Error instance (optional)
86
* @param props - Additional error properties (optional)
87
*/
88
function syncError(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any>): void;
89
90
type MockError = Error | string;
91
```
92
93
**Usage Examples:**
94
95
```typescript
96
import fs from "node:fs";
97
import { syncError } from "mm";
98
99
// Mock with simple error message
100
syncError(fs, "readFileSync", "File not found");
101
try {
102
fs.readFileSync("missing.txt");
103
} catch (err) {
104
console.log(err.message); // => "File not found"
105
console.log(err.name); // => "MockError"
106
}
107
108
// Mock with custom Error instance
109
const customError = new Error("Permission denied");
110
syncError(fs, "readFileSync", customError);
111
112
// Mock with error properties
113
syncError(fs, "readFileSync", "Access denied", {
114
code: "EACCES",
115
errno: -13,
116
path: "/restricted/file.txt"
117
});
118
119
try {
120
fs.readFileSync("/restricted/file.txt");
121
} catch (err) {
122
console.log(err.code); // => "EACCES"
123
console.log(err.errno); // => -13
124
console.log(err.path); // => "/restricted/file.txt"
125
}
126
```
127
128
### Default Error Creation
129
130
When no error is provided, mm creates a default error:
131
132
```typescript
133
import { syncError } from "mm";
134
135
// No error provided - creates default
136
syncError(someObject, "method");
137
138
try {
139
someObject.method();
140
} catch (err) {
141
console.log(err.message); // => "mm mock error"
142
console.log(err.name); // => "MockError"
143
}
144
```
145
146
## Synchronous vs Asynchronous Considerations
147
148
Synchronous mocks are ideal for:
149
150
- **Pure functions**: Functions that don't perform I/O operations
151
- **Data transformations**: Parsing, formatting, validation functions
152
- **Configuration access**: Getting settings, environment variables
153
- **Synchronous APIs**: File system sync operations, crypto functions
154
- **Testing error conditions**: Immediate error simulation
155
156
**Usage Examples:**
157
158
```typescript
159
import crypto from "node:crypto";
160
import { syncData, syncError } from "mm";
161
162
// Mock crypto operations
163
syncData(crypto, "randomBytes", Buffer.from("mock-random-data"));
164
const mockRandom = crypto.randomBytes(16); // Deterministic for testing
165
166
// Mock parsing functions
167
const jsonParser = {
168
parse: (str: string) => JSON.parse(str)
169
};
170
171
syncError(jsonParser, "parse", "Invalid JSON", {
172
position: 42
173
});
174
175
try {
176
jsonParser.parse("invalid json");
177
} catch (err) {
178
console.log(err.position); // => 42
179
}
180
```
181
182
## Integration with Spy Functionality
183
184
All synchronous mocks automatically include spy properties for call tracking:
185
186
```typescript
187
import { syncData } from "mm";
188
189
const calculator = {
190
multiply: (a: number, b: number) => a * b
191
};
192
193
syncData(calculator, "multiply", 42);
194
195
const result1 = calculator.multiply(3, 4); // => 42
196
const result2 = calculator.multiply(7, 8); // => 42
197
198
console.log(calculator.multiply.called); // => 2
199
console.log(calculator.multiply.calledArguments); // => [[3, 4], [7, 8]]
200
console.log(calculator.multiply.lastCalledArguments); // => [7, 8]
201
```
202
203
## Error Types and Properties
204
205
Synchronous error mocking supports rich error information:
206
207
```typescript
208
import { syncError } from "mm";
209
210
const validator = {
211
validate: (data: any) => { /* validation logic */ }
212
};
213
214
// Mock validation error with detailed information
215
syncError(validator, "validate", "Validation failed", {
216
field: "email",
217
code: "INVALID_FORMAT",
218
value: "not-an-email",
219
expected: "Valid email address"
220
});
221
222
try {
223
validator.validate({ email: "not-an-email" });
224
} catch (err) {
225
console.log(err.field); // => "email"
226
console.log(err.code); // => "INVALID_FORMAT"
227
console.log(err.value); // => "not-an-email"
228
console.log(err.expected); // => "Valid email address"
229
}
230
```
231
232
## Types
233
234
```typescript { .api }
235
// Error types for synchronous mocking
236
type MockError = Error | string;
237
238
// Spy properties added to all mocked functions
239
interface SpyProperties {
240
called: number;
241
calledArguments: any[][];
242
lastCalledArguments: any[];
243
}
244
```