0
# Conditional Mocking
1
2
Advanced mocking capabilities that allow selective mocking based on URL patterns or custom predicates. Enables fine-grained control over which requests are mocked versus which use real fetch.
3
4
## Capabilities
5
6
### Is Mocking
7
8
Checks whether a given request should be mocked based on current mock conditions.
9
10
```javascript { .api }
11
/**
12
* Check if a request should be mocked based on current conditions
13
* @param input - URL string or Request object to check
14
* @param reqInit - Optional RequestInit for URL string inputs
15
* @returns Boolean indicating if request will be mocked
16
*/
17
fetch.isMocking(input, reqInit);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
// Check if URL will be mocked
24
const willMock = fetch.isMocking("/api/users");
25
26
// Check with Request object
27
const request = new Request("/api/data", { method: "POST" });
28
const shouldMock = fetch.isMocking(request);
29
30
// Use in conditional logic
31
if (fetch.isMocking("/api/critical")) {
32
console.log("Critical API is being mocked");
33
}
34
```
35
36
### Do Mock
37
38
Enables mocking for all requests, optionally with a default response.
39
40
```javascript { .api }
41
/**
42
* Enable mocking for all requests
43
* @param bodyOrFunction - Optional default response body or function
44
* @param init - Optional response configuration
45
* @returns FetchMock instance for chaining
46
*/
47
fetch.doMock(bodyOrFunction, init);
48
```
49
50
**Usage Examples:**
51
52
```javascript
53
// Enable mocking with default empty response
54
fetch.doMock();
55
56
// Enable mocking with default response
57
fetch.doMock("Default mock response");
58
59
// Enable mocking with JSON response
60
fetch.doMock(JSON.stringify({ mocked: true }), {
61
status: 200,
62
headers: { "Content-Type": "application/json" }
63
});
64
```
65
66
### Do Mock Once
67
68
Enables mocking for the next request only, optionally with a response.
69
70
```javascript { .api }
71
/**
72
* Enable mocking for the next request only
73
* @param bodyOrFunction - Optional response body or function
74
* @param init - Optional response configuration
75
* @returns FetchMock instance for chaining
76
*/
77
fetch.doMockOnce(bodyOrFunction, init);
78
```
79
80
### Mock Once (Alias)
81
82
Convenient alias for `doMockOnce`.
83
84
```javascript { .api }
85
/**
86
* Alias for doMockOnce - enable mocking for the next request only
87
* @param bodyOrFunction - Optional response body or function
88
* @param init - Optional response configuration
89
* @returns FetchMock instance for chaining
90
*/
91
fetch.mockOnce(bodyOrFunction, init);
92
```
93
94
### Mock If
95
96
Enables mocking only for requests matching the specified URL pattern or predicate function.
97
98
```javascript { .api }
99
/**
100
* Mock requests matching URL pattern or predicate
101
* @param urlOrPredicate - URL string, RegExp, or predicate function
102
* @param bodyOrFunction - Optional response body or function
103
* @param init - Optional response configuration
104
* @returns FetchMock instance for chaining
105
*/
106
fetch.mockIf(urlOrPredicate, bodyOrFunction, init);
107
```
108
109
### Do Mock If (Alias)
110
111
Alias for `mockIf` providing the same functionality.
112
113
```javascript { .api }
114
/**
115
* Alias for mockIf - mock requests matching URL pattern or predicate
116
* @param urlOrPredicate - URL string, RegExp, or predicate function
117
* @param bodyOrFunction - Optional response body or function
118
* @param init - Optional response configuration
119
* @returns FetchMock instance for chaining
120
*/
121
fetch.doMockIf(urlOrPredicate, bodyOrFunction, init);
122
```
123
124
**Usage Examples:**
125
126
```javascript
127
// Mock specific URL
128
fetch.mockIf("/api/users", JSON.stringify({ users: [] }));
129
130
// Mock URLs matching regex
131
fetch.mockIf(/\/api\/posts\/\d+/, JSON.stringify({ post: {} }));
132
133
// Mock with predicate function
134
fetch.mockIf(
135
(request) => request.method === "POST" && request.url.includes("/api/"),
136
JSON.stringify({ success: true })
137
);
138
139
// Mock external APIs only
140
fetch.mockIf(
141
(request) => request.url.startsWith("https://external-api.com"),
142
(request) => {
143
if (request.url.includes("/users")) {
144
return Promise.resolve(JSON.stringify({ users: [] }));
145
}
146
return Promise.resolve(JSON.stringify({ data: "mock" }));
147
}
148
);
149
```
150
151
### Mock Once If
152
153
Enables mocking for the next request only if it matches the URL pattern or predicate.
154
155
```javascript { .api }
156
/**
157
* Mock next request if it matches URL pattern or predicate
158
* @param urlOrPredicate - URL string, RegExp, or predicate function
159
* @param bodyOrFunction - Optional response body or function
160
* @param init - Optional response configuration
161
* @returns FetchMock instance for chaining
162
*/
163
fetch.mockOnceIf(urlOrPredicate, bodyOrFunction, init);
164
```
165
166
### Do Mock Once If (Alias)
167
168
Alias for `mockOnceIf`.
169
170
```javascript { .api }
171
/**
172
* Alias for mockOnceIf - mock next request if it matches URL pattern or predicate
173
* @param urlOrPredicate - URL string, RegExp, or predicate function
174
* @param bodyOrFunction - Optional response body or function
175
* @param init - Optional response configuration
176
* @returns FetchMock instance for chaining
177
*/
178
fetch.doMockOnceIf(urlOrPredicate, bodyOrFunction, init);
179
```
180
181
### Don't Mock
182
183
Disables mocking for all requests, using real fetch instead.
184
185
```javascript { .api }
186
/**
187
* Disable mocking for all requests (use real fetch)
188
* @param bodyOrFunction - Optional fallback response (typically unused)
189
* @param init - Optional response configuration (typically unused)
190
* @returns FetchMock instance for chaining
191
*/
192
fetch.dontMock(bodyOrFunction, init);
193
```
194
195
**Usage Examples:**
196
197
```javascript
198
// Disable all mocking
199
fetch.dontMock();
200
201
// Use in setup to default to real fetch
202
beforeEach(() => {
203
fetch.resetMocks();
204
fetch.dontMock(); // Use real fetch unless explicitly mocked
205
});
206
```
207
208
### Don't Mock Once
209
210
Disables mocking for the next request only, using real fetch.
211
212
```javascript { .api }
213
/**
214
* Disable mocking for the next request only (use real fetch)
215
* @param bodyOrFunction - Optional fallback response (typically unused)
216
* @param init - Optional response configuration (typically unused)
217
* @returns FetchMock instance for chaining
218
*/
219
fetch.dontMockOnce(bodyOrFunction, init);
220
```
221
222
### Don't Mock If
223
224
Disables mocking for requests matching the URL pattern or predicate, using real fetch for those requests.
225
226
```javascript { .api }
227
/**
228
* Don't mock requests matching URL pattern or predicate (use real fetch)
229
* @param urlOrPredicate - URL string, RegExp, or predicate function
230
* @param bodyOrFunction - Optional fallback response for non-matching requests
231
* @param init - Optional response configuration for non-matching requests
232
* @returns FetchMock instance for chaining
233
*/
234
fetch.dontMockIf(urlOrPredicate, bodyOrFunction, init);
235
```
236
237
**Usage Examples:**
238
239
```javascript
240
// Don't mock specific internal API (use real fetch)
241
fetch.dontMockIf("/api/health");
242
243
// Don't mock localhost requests
244
fetch.dontMockIf((request) => request.url.includes("localhost"));
245
246
// Mock everything except health checks
247
fetch.mockResponse("Default mock");
248
fetch.dontMockIf(/\/health$/);
249
```
250
251
### Don't Mock Once If
252
253
Disables mocking for the next request only if it matches the URL pattern or predicate.
254
255
```javascript { .api }
256
/**
257
* Don't mock next request if it matches URL pattern or predicate
258
* @param urlOrPredicate - URL string, RegExp, or predicate function
259
* @param bodyOrFunction - Optional fallback response for non-matching requests
260
* @param init - Optional response configuration for non-matching requests
261
* @returns FetchMock instance for chaining
262
*/
263
fetch.dontMockOnceIf(urlOrPredicate, bodyOrFunction, init);
264
```
265
266
## Types
267
268
```typescript { .api }
269
/**
270
* Union type for URL matching parameters
271
*/
272
type UrlOrPredicate = string | RegExp | ((input: Request) => boolean);
273
```
274
275
## Usage Patterns
276
277
### Environment-Based Mocking
278
279
```javascript
280
// Mock external APIs in test environment
281
if (process.env.NODE_ENV === "test") {
282
fetch.mockIf(
283
(request) => !request.url.includes("localhost"),
284
"Mock response for external APIs"
285
);
286
}
287
```
288
289
### Selective API Mocking
290
291
```javascript
292
// Mock slow/unreliable APIs, use real fetch for others
293
fetch.dontMock(); // Default to real fetch
294
fetch.mockIf(/api\.slow-service\.com/, "Fast mock response");
295
fetch.mockIf(/api\.unreliable\.com/, JSON.stringify({ data: [] }));
296
```
297
298
### Progressive Enhancement
299
300
```javascript
301
// Start with real fetch, add mocks as needed
302
beforeEach(() => {
303
fetch.dontMock();
304
305
// Only mock specific problematic endpoints
306
fetch.mockIf("/api/flaky-endpoint", "Stable mock");
307
});
308
```