@sgedda/mockifyer-fetch 1.7.0 → 1.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/METRO_CONFIG.md +60 -0
- package/dist/index.js +18 -165
- package/dist/metro-config.d.ts +89 -8
- package/dist/metro-config.js +126 -8
- package/dist/metro-sync-middleware.js +36 -19
- package/dist/react-native.js +8 -7
- package/package.json +4 -3
- package/src/clients/fetch-client.d.ts +14 -0
- package/src/clients/fetch-client.d.ts.map +1 -0
- package/src/clients/fetch-client.js +75 -0
- package/src/index.d.ts +10 -0
- package/src/index.d.ts.map +1 -0
- package/src/index.js +966 -0
- package/src/index.ts +18 -166
- package/src/metro-config.ts +153 -9
- package/src/metro-sync-middleware.ts +40 -20
- package/src/react-native.d.ts +45 -0
- package/src/react-native.d.ts.map +1 -0
- package/src/react-native.js +141 -0
- package/src/react-native.ts +8 -7
package/METRO_CONFIG.md
CHANGED
|
@@ -6,6 +6,8 @@ Mockifyer requires Metro bundler configuration to stub Node.js built-in modules
|
|
|
6
6
|
|
|
7
7
|
Use the provided helper function to configure Metro automatically:
|
|
8
8
|
|
|
9
|
+
### Basic Setup (FS Stubbing Only)
|
|
10
|
+
|
|
9
11
|
```javascript
|
|
10
12
|
// metro.config.js
|
|
11
13
|
const { getDefaultConfig } = require('expo/metro-config');
|
|
@@ -15,6 +17,32 @@ const config = getDefaultConfig(__dirname);
|
|
|
15
17
|
module.exports = configureMetroForMockifyer(config);
|
|
16
18
|
```
|
|
17
19
|
|
|
20
|
+
### With Sync Middleware (For Hybrid Provider)
|
|
21
|
+
|
|
22
|
+
If you're using the Hybrid Provider to save files to both device and project folder:
|
|
23
|
+
|
|
24
|
+
```javascript
|
|
25
|
+
// metro.config.js
|
|
26
|
+
const { getDefaultConfig } = require('expo/metro-config');
|
|
27
|
+
const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
28
|
+
|
|
29
|
+
const config = getDefaultConfig(__dirname);
|
|
30
|
+
|
|
31
|
+
// One function call handles BOTH:
|
|
32
|
+
// 1. FS/path stubbing (for bundling)
|
|
33
|
+
// 2. Sync middleware (for Hybrid Provider to save files to project folder)
|
|
34
|
+
module.exports = configureMetroForMockifyer(config, {
|
|
35
|
+
syncMiddleware: {
|
|
36
|
+
projectRoot: __dirname,
|
|
37
|
+
mockDataPath: './mock-data',
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
This automatically sets up:
|
|
43
|
+
- ✅ Node.js module stubbing (`fs`, `path`, `assert`, `util`)
|
|
44
|
+
- ✅ Sync middleware for Hybrid Provider (saves files to project folder)
|
|
45
|
+
|
|
18
46
|
## Manual Setup
|
|
19
47
|
|
|
20
48
|
If you prefer manual configuration or need more control:
|
|
@@ -52,8 +80,20 @@ module.exports = config;
|
|
|
52
80
|
|
|
53
81
|
## Why This Is Needed
|
|
54
82
|
|
|
83
|
+
### FS/Path Stubbing
|
|
84
|
+
|
|
55
85
|
Mockifyer packages use Node.js built-in modules (`fs`, `path`) for filesystem operations. These modules aren't available in React Native, so Metro needs to stub them during bundling. The stubs are empty modules that allow bundling to succeed while the code gracefully handles their absence at runtime.
|
|
56
86
|
|
|
87
|
+
**Note:** With conditional imports (added in recent versions), FS stubbing is optional - the code handles missing modules gracefully. However, Metro config is still recommended to prevent bundling errors.
|
|
88
|
+
|
|
89
|
+
### Sync Middleware (Optional)
|
|
90
|
+
|
|
91
|
+
If you're using the **Hybrid Provider**, you need sync middleware to save files to your project folder. The Hybrid Provider saves mocks to both:
|
|
92
|
+
1. Device filesystem (via Expo FileSystem)
|
|
93
|
+
2. Project folder (via Metro HTTP endpoint)
|
|
94
|
+
|
|
95
|
+
The sync middleware handles the Metro endpoint (`/mockifyer-save`) that writes files to your project folder.
|
|
96
|
+
|
|
57
97
|
## Modules Stubbed
|
|
58
98
|
|
|
59
99
|
- `fs` - Used by FilesystemProvider (not used in React Native - use ExpoFileSystemProvider instead)
|
|
@@ -95,3 +135,23 @@ config.resolver.extraNodeModules = { /* ... */ };
|
|
|
95
135
|
module.exports = configureMetroForMockifyer(config);
|
|
96
136
|
```
|
|
97
137
|
|
|
138
|
+
### Files Not Appearing in Project Folder (Hybrid Provider)
|
|
139
|
+
|
|
140
|
+
If you're using Hybrid Provider but files aren't appearing in your project folder:
|
|
141
|
+
|
|
142
|
+
1. **Check Metro is running**: Hybrid Provider requires Metro to be running
|
|
143
|
+
2. **Check sync middleware is configured**: Make sure you passed `syncMiddleware` options to `configureMetroForMockifyer`
|
|
144
|
+
3. **Check Metro port**: Ensure Metro port matches (default: 8081)
|
|
145
|
+
4. **Check logs**: Look for `[HybridProvider]` messages in your app logs
|
|
146
|
+
|
|
147
|
+
Example with sync middleware:
|
|
148
|
+
|
|
149
|
+
```javascript
|
|
150
|
+
module.exports = configureMetroForMockifyer(config, {
|
|
151
|
+
syncMiddleware: {
|
|
152
|
+
projectRoot: __dirname,
|
|
153
|
+
mockDataPath: './mock-data',
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
package/dist/index.js
CHANGED
|
@@ -31,6 +31,7 @@ catch (e) {
|
|
|
31
31
|
}
|
|
32
32
|
// Import from core package
|
|
33
33
|
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
34
|
+
const mockifyer_core_2 = require("@sgedda/mockifyer-core");
|
|
34
35
|
const fetch_client_1 = require("./clients/fetch-client");
|
|
35
36
|
class MockifyerClass {
|
|
36
37
|
constructor(config) {
|
|
@@ -50,7 +51,7 @@ class MockifyerClass {
|
|
|
50
51
|
}
|
|
51
52
|
// Validate and normalize conflicting settings
|
|
52
53
|
if (config.recordMode && config.failOnMissingMock) {
|
|
53
|
-
|
|
54
|
+
mockifyer_core_2.logger.warn('[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
|
|
54
55
|
'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
|
|
55
56
|
'Setting failOnMissingMock to false.');
|
|
56
57
|
config.failOnMissingMock = false;
|
|
@@ -59,7 +60,7 @@ class MockifyerClass {
|
|
|
59
60
|
if (config.similarMatchIgnoreAllQueryParams &&
|
|
60
61
|
config.similarMatchRequiredParams &&
|
|
61
62
|
config.similarMatchRequiredParams.length > 0) {
|
|
62
|
-
|
|
63
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
|
|
63
64
|
'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
|
|
64
65
|
'similarMatchRequiredParams will be ignored.');
|
|
65
66
|
// Clear similarMatchRequiredParams to avoid confusion
|
|
@@ -80,24 +81,8 @@ class MockifyerClass {
|
|
|
80
81
|
// Store config BEFORE any modifications
|
|
81
82
|
this.config = { ...config }; // Create a copy to avoid mutations
|
|
82
83
|
// Initialize test generator if test generation is enabled
|
|
83
|
-
console.log('[Mockifyer-Fetch] HÖHÖHÖ 🔧 Constructor - Full config received:', JSON.stringify({
|
|
84
|
-
generateTests: config.generateTests,
|
|
85
|
-
recordMode: config.recordMode,
|
|
86
|
-
mockDataPath: config.mockDataPath,
|
|
87
|
-
databaseProvider: config.databaseProvider?.type
|
|
88
|
-
}, null, 2));
|
|
89
|
-
console.log('[Mockifyer-Fetch] 🔧 Constructor - generateTests config:', JSON.stringify(config.generateTests, null, 2));
|
|
90
|
-
console.log('[Mockifyer-Fetch] 🔧 Constructor - config.generateTests?.enabled:', config.generateTests?.enabled);
|
|
91
84
|
if (config.generateTests?.enabled) {
|
|
92
|
-
console.log('[Mockifyer-Fetch] ✅ Initializing test generator...');
|
|
93
85
|
this.testGenerator = new mockifyer_core_1.TestGenerator();
|
|
94
|
-
console.log('[Mockifyer-Fetch] ✅ Test generator initialized:', !!this.testGenerator);
|
|
95
|
-
}
|
|
96
|
-
else {
|
|
97
|
-
console.log('[Mockifyer-Fetch] ⚠️ Test generation NOT enabled in config');
|
|
98
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - config.generateTests:', config.generateTests);
|
|
99
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - typeof config.generateTests:', typeof config.generateTests);
|
|
100
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - config keys:', Object.keys(config));
|
|
101
86
|
}
|
|
102
87
|
// Initialize database provider if specified
|
|
103
88
|
if (config.databaseProvider && config.databaseProvider.type) {
|
|
@@ -106,7 +91,7 @@ class MockifyerClass {
|
|
|
106
91
|
// Handle async initialization (expo-filesystem provider has async initialize)
|
|
107
92
|
if (initResult instanceof Promise) {
|
|
108
93
|
initResult.catch((error) => {
|
|
109
|
-
|
|
94
|
+
mockifyer_core_2.logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
|
|
110
95
|
});
|
|
111
96
|
}
|
|
112
97
|
}
|
|
@@ -201,24 +186,14 @@ class MockifyerClass {
|
|
|
201
186
|
return undefined;
|
|
202
187
|
}
|
|
203
188
|
const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
|
|
204
|
-
console.log('[Mockifyer-Fetch] 📁 Mock data path:', {
|
|
205
|
-
original: this.config.mockDataPath,
|
|
206
|
-
resolved: resolvedMockDataPath,
|
|
207
|
-
exists: fs.existsSync(resolvedMockDataPath)
|
|
208
|
-
});
|
|
209
189
|
if (!fs.existsSync(resolvedMockDataPath)) {
|
|
210
190
|
console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
|
|
211
191
|
return undefined;
|
|
212
192
|
}
|
|
213
193
|
const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath);
|
|
214
194
|
const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
|
|
215
|
-
console.log('[Mockifyer-Fetch] 📁 Scenario path:', {
|
|
216
|
-
scenario: currentScenario,
|
|
217
|
-
path: scenarioPath,
|
|
218
|
-
exists: fs.existsSync(scenarioPath)
|
|
219
|
-
});
|
|
220
195
|
if (!fs.existsSync(scenarioPath)) {
|
|
221
|
-
|
|
196
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
|
|
222
197
|
return undefined;
|
|
223
198
|
}
|
|
224
199
|
const files = fs.readdirSync(scenarioPath)
|
|
@@ -226,13 +201,6 @@ class MockifyerClass {
|
|
|
226
201
|
const requestKey = this.generateRequestKey(request);
|
|
227
202
|
let exactMatch;
|
|
228
203
|
let similarMatch;
|
|
229
|
-
console.log('[Mockifyer-Fetch] 🔍 Searching for mock:', {
|
|
230
|
-
requestKey,
|
|
231
|
-
useSimilarMatch: this.config.useSimilarMatch,
|
|
232
|
-
similarMatchIgnoreAllQueryParams: this.config.similarMatchIgnoreAllQueryParams,
|
|
233
|
-
filesCount: files.length,
|
|
234
|
-
files: files.slice(0, 5) // Show first 5 files for debugging
|
|
235
|
-
});
|
|
236
204
|
for (const file of files) {
|
|
237
205
|
try {
|
|
238
206
|
const filePath = path.join(scenarioPath, file);
|
|
@@ -243,7 +211,6 @@ class MockifyerClass {
|
|
|
243
211
|
}
|
|
244
212
|
const mockKey = this.generateRequestKey(mockData.request);
|
|
245
213
|
if (mockKey === requestKey) {
|
|
246
|
-
console.log('[Mockifyer-Fetch] ✅ Exact match found:', file);
|
|
247
214
|
exactMatch = { mockData, filename: file, filePath };
|
|
248
215
|
break;
|
|
249
216
|
}
|
|
@@ -289,22 +256,11 @@ class MockifyerClass {
|
|
|
289
256
|
}
|
|
290
257
|
}
|
|
291
258
|
const pathnameMatch = exactPathnameMatch || patternMatch;
|
|
292
|
-
|
|
293
|
-
file,
|
|
294
|
-
requestPathname,
|
|
295
|
-
mockPathname,
|
|
296
|
-
requestMethod: (request.method || 'GET').toUpperCase(),
|
|
297
|
-
mockMethod: (mockData.request.method || 'GET').toUpperCase(),
|
|
298
|
-
exactPathnameMatch,
|
|
299
|
-
patternMatch,
|
|
300
|
-
pathnameMatch,
|
|
301
|
-
methodMatch
|
|
302
|
-
});
|
|
259
|
+
// Check similar match
|
|
303
260
|
if (pathnameMatch && methodMatch) {
|
|
304
261
|
// If ignoreAllQueryParams is set, skip query param checking entirely
|
|
305
262
|
if (this.config.similarMatchIgnoreAllQueryParams) {
|
|
306
263
|
// Ignore all query params, match on path and method only
|
|
307
|
-
console.log('[Mockifyer-Fetch] ✅ Similar match found (ignoring query params):', file);
|
|
308
264
|
}
|
|
309
265
|
else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
|
|
310
266
|
// Check if required parameters match (if configured)
|
|
@@ -331,7 +287,7 @@ class MockifyerClass {
|
|
|
331
287
|
}
|
|
332
288
|
}
|
|
333
289
|
catch (error) {
|
|
334
|
-
|
|
290
|
+
mockifyer_core_2.logger.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
|
|
335
291
|
}
|
|
336
292
|
}
|
|
337
293
|
return exactMatch || similarMatch;
|
|
@@ -376,22 +332,7 @@ class MockifyerClass {
|
|
|
376
332
|
// Store request start time for duration calculation
|
|
377
333
|
config.__mockifyer_startTime = Date.now();
|
|
378
334
|
const cachedMock = await this.findBestMatchingMock(request);
|
|
379
|
-
if
|
|
380
|
-
console.log('[Mockifyer-Fetch] ⚠️ No mock found for request:', {
|
|
381
|
-
method: request.method,
|
|
382
|
-
url: request.url,
|
|
383
|
-
queryParams: request.queryParams,
|
|
384
|
-
requestKey: requestKey,
|
|
385
|
-
mockDataPath: this.config.mockDataPath,
|
|
386
|
-
hasDatabaseProvider: !!this.databaseProvider
|
|
387
|
-
});
|
|
388
|
-
}
|
|
389
|
-
else {
|
|
390
|
-
console.log('[Mockifyer-Fetch] ✅ Mock found:', {
|
|
391
|
-
filename: cachedMock.filename,
|
|
392
|
-
url: request.url
|
|
393
|
-
});
|
|
394
|
-
}
|
|
335
|
+
// Return cached mock if found
|
|
395
336
|
if (cachedMock) {
|
|
396
337
|
const { mockData, filename, filePath } = cachedMock;
|
|
397
338
|
const responseHeaders = {
|
|
@@ -512,34 +453,22 @@ class MockifyerClass {
|
|
|
512
453
|
if (responseDataStr && (responseDataStr.includes('/mockifyer-save') ||
|
|
513
454
|
responseDataStr.includes('/mockifyer-clear') ||
|
|
514
455
|
responseDataStr.includes('/mockifyer-sync'))) {
|
|
515
|
-
console.log('[Mockifyer-Fetch] ⚠️ Bypassing Mockifyer - sync endpoint in response data');
|
|
516
456
|
return response;
|
|
517
457
|
}
|
|
518
458
|
}
|
|
519
459
|
catch (e) {
|
|
520
460
|
// Ignore errors - continue processing
|
|
521
|
-
|
|
461
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data:', e);
|
|
522
462
|
}
|
|
523
463
|
const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
|
|
524
464
|
const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
|
|
525
465
|
if (isMocked || isLimitReached) {
|
|
526
|
-
console.log('[Mockifyer-Fetch] Response is mocked, skipping save' + (isLimitReached ? ' (limit reached)' : ''));
|
|
527
466
|
return response;
|
|
528
467
|
}
|
|
529
468
|
// Only save if recordMode is enabled
|
|
530
469
|
if (this.config.recordMode) {
|
|
531
|
-
console.log('[Mockifyer-Fetch] ✅ recordMode enabled, saving response');
|
|
532
|
-
console.log('[Mockifyer-Fetch] Response URL:', response.config?.url);
|
|
533
|
-
console.log('[Mockifyer-Fetch] Response method:', response.config?.method);
|
|
534
|
-
console.log('[Mockifyer-Fetch] Response status:', response.status);
|
|
535
|
-
console.log('[Mockifyer-Fetch] Response config.data:', response.config?.data);
|
|
536
|
-
console.log('[Mockifyer-Fetch] Response config exists:', !!response.config);
|
|
537
470
|
await this.saveResponse(response);
|
|
538
471
|
}
|
|
539
|
-
else {
|
|
540
|
-
console.log('[Mockifyer-Fetch] ⚠️ recordMode disabled, not saving response');
|
|
541
|
-
console.log('[Mockifyer-Fetch] Current config.recordMode:', this.config.recordMode);
|
|
542
|
-
}
|
|
543
472
|
return response;
|
|
544
473
|
}, async (error) => {
|
|
545
474
|
const requestKey = error.config?.__mockifyer_requestKey;
|
|
@@ -550,22 +479,8 @@ class MockifyerClass {
|
|
|
550
479
|
});
|
|
551
480
|
}
|
|
552
481
|
async saveResponse(response) {
|
|
553
|
-
console.log('[Mockifyer-Fetch] 💾 saveResponse called');
|
|
554
|
-
console.log('[Mockifyer-Fetch] 💾 Config at saveResponse:', {
|
|
555
|
-
generateTestsEnabled: this.config.generateTests?.enabled,
|
|
556
|
-
hasGenerateTests: !!this.config.generateTests,
|
|
557
|
-
recordMode: this.config.recordMode,
|
|
558
|
-
hasDatabaseProvider: !!this.databaseProvider
|
|
559
|
-
});
|
|
560
|
-
console.log('[Mockifyer-Fetch] saveResponse - response.config:', response.config ? {
|
|
561
|
-
url: response.config.url,
|
|
562
|
-
method: response.config.method,
|
|
563
|
-
hasData: !!response.config.data,
|
|
564
|
-
dataType: typeof response.config.data
|
|
565
|
-
} : 'NO CONFIG');
|
|
566
482
|
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
567
483
|
if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
|
|
568
|
-
console.log('[Mockifyer-Fetch] ⚠️ saveResponse: BLOCKING - bypass flag set');
|
|
569
484
|
return;
|
|
570
485
|
}
|
|
571
486
|
// CRITICAL: Skip saving responses from Mockifyer sync endpoints and Resend API FIRST
|
|
@@ -575,7 +490,6 @@ class MockifyerClass {
|
|
|
575
490
|
url.includes('/mockifyer-clear') ||
|
|
576
491
|
url.includes('/mockifyer-sync') ||
|
|
577
492
|
url.includes('api.resend.com'))) {
|
|
578
|
-
console.log('[Mockifyer-Fetch] ⚠️ Skipping save - Resend API request:', url);
|
|
579
493
|
return;
|
|
580
494
|
}
|
|
581
495
|
// CRITICAL: Check response data for sync endpoint references and Metro rejection messages
|
|
@@ -606,7 +520,7 @@ class MockifyerClass {
|
|
|
606
520
|
}
|
|
607
521
|
catch (e) {
|
|
608
522
|
// Ignore JSON stringify errors
|
|
609
|
-
|
|
523
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
|
|
610
524
|
}
|
|
611
525
|
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
612
526
|
const rawParams = response.config.params || {};
|
|
@@ -656,39 +570,15 @@ class MockifyerClass {
|
|
|
656
570
|
duration,
|
|
657
571
|
sessionId: this.currentSessionId
|
|
658
572
|
};
|
|
659
|
-
console.log('[Mockifyer-Fetch] Saving mock data:', {
|
|
660
|
-
method: mockData.request.method,
|
|
661
|
-
url: mockData.request.url,
|
|
662
|
-
hasRequestData: !!mockData.request.data,
|
|
663
|
-
responseStatus: mockData.response.status,
|
|
664
|
-
provider: this.config.databaseProvider?.type || 'filesystem'
|
|
665
|
-
});
|
|
666
573
|
// Use database provider if available, otherwise fallback to filesystem
|
|
667
574
|
if (this.databaseProvider) {
|
|
668
575
|
try {
|
|
669
|
-
console.log('[Mockifyer-Fetch] 💾 Saving mock via database provider...');
|
|
670
576
|
await this.databaseProvider.save(mockData);
|
|
671
|
-
console.log('[Mockifyer-Fetch] ✅ Successfully saved mock using provider');
|
|
672
577
|
// Generate test if enabled (try to write test files even with database provider)
|
|
673
|
-
//
|
|
674
|
-
console.log('[Mockifyer-Fetch] 🔍 Checking test generation config...');
|
|
675
|
-
console.log('[Mockifyer-Fetch] 🔍 this.config.generateTests:', JSON.stringify(this.config.generateTests, null, 2));
|
|
676
|
-
console.log('[Mockifyer-Fetch] 🔍 this.config.generateTests?.enabled:', this.config.generateTests?.enabled);
|
|
578
|
+
// Generate test if enabled
|
|
677
579
|
if (this.config.generateTests?.enabled) {
|
|
678
|
-
console.log('[Mockifyer-Fetch] 🔧 Test generation enabled, attempting to generate test...');
|
|
679
|
-
console.log('[Mockifyer-Fetch] 🔧 Test generator available:', !!this.testGenerator);
|
|
680
|
-
console.log('[Mockifyer-Fetch] 🔧 fs available:', !!fs);
|
|
681
|
-
console.log('[Mockifyer-Fetch] 🔧 path available:', !!path);
|
|
682
580
|
await this.generateTestForMock(mockData);
|
|
683
581
|
}
|
|
684
|
-
else {
|
|
685
|
-
console.log('[Mockifyer-Fetch] ⚠️ Test generation NOT enabled - skipping');
|
|
686
|
-
console.log('[Mockifyer-Fetch] ⚠️ Config check:', {
|
|
687
|
-
hasGenerateTests: !!this.config.generateTests,
|
|
688
|
-
enabled: this.config.generateTests?.enabled,
|
|
689
|
-
fullConfig: JSON.stringify(this.config.generateTests)
|
|
690
|
-
});
|
|
691
|
-
}
|
|
692
582
|
}
|
|
693
583
|
catch (error) {
|
|
694
584
|
console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`, error);
|
|
@@ -714,7 +604,7 @@ class MockifyerClass {
|
|
|
714
604
|
}
|
|
715
605
|
const filePath = path.join(scenarioPath, filename);
|
|
716
606
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
717
|
-
|
|
607
|
+
mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
|
|
718
608
|
// Generate test if enabled
|
|
719
609
|
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
720
610
|
await this.generateTestForMock(mockData);
|
|
@@ -775,20 +665,13 @@ class MockifyerClass {
|
|
|
775
665
|
if (!testFs) {
|
|
776
666
|
try {
|
|
777
667
|
testFs = require('fs');
|
|
778
|
-
console.log('[Mockifyer] ✅ Found fs module for test generation');
|
|
779
668
|
}
|
|
780
669
|
catch (e) {
|
|
781
|
-
console.log('[Mockifyer] ⚠️ Test generation skipped: fs not available');
|
|
782
|
-
console.log('[Mockifyer] 💡 Tip: Test generation requires Node.js fs module.');
|
|
783
|
-
console.log('[Mockifyer] 💡 In React Native, tests are generated in Metro bundler (Node.js environment).');
|
|
784
670
|
return;
|
|
785
671
|
}
|
|
786
672
|
}
|
|
787
673
|
// Use the available fs - ensure it's defined and has required methods
|
|
788
674
|
if (!testFs || typeof testFs.writeFileSync !== 'function' || typeof testFs.mkdirSync !== 'function') {
|
|
789
|
-
console.log('[Mockifyer] ⚠️ Test generation skipped: fs module missing required methods');
|
|
790
|
-
console.log('[Mockifyer] 💡 fs.writeFileSync:', typeof testFs?.writeFileSync);
|
|
791
|
-
console.log('[Mockifyer] 💡 fs.mkdirSync:', typeof testFs?.mkdirSync);
|
|
792
675
|
return;
|
|
793
676
|
}
|
|
794
677
|
const fsToUse = testFs;
|
|
@@ -801,31 +684,24 @@ class MockifyerClass {
|
|
|
801
684
|
groupBy: this.config.generateTests?.groupBy || 'file',
|
|
802
685
|
httpClientType: 'fetch'
|
|
803
686
|
};
|
|
804
|
-
console.log('[Mockifyer] 📝 Test generation options:', JSON.stringify(options, null, 2));
|
|
805
687
|
const testCode = this.testGenerator.generateTest(mockData, options);
|
|
806
688
|
const testFilePath = this.testGenerator.determineTestFilePath(mockData, options);
|
|
807
|
-
console.log('[Mockifyer] 📝 Generated test file path:', testFilePath);
|
|
808
689
|
// Resolve to absolute path (relative to process.cwd() which should be project root in Metro)
|
|
809
690
|
// Use our fallback path resolution that works even when path module is stubbed
|
|
810
691
|
const absoluteTestPath = this.resolvePath(testFilePath);
|
|
811
|
-
console.log('[Mockifyer] 📝 Final absolute test path:', absoluteTestPath);
|
|
812
692
|
// Ensure test directory exists
|
|
813
693
|
const testDir = this.dirname(absoluteTestPath);
|
|
814
|
-
console.log('[Mockifyer] 📝 Test directory:', testDir);
|
|
815
694
|
if (!fsToUse.existsSync(testDir)) {
|
|
816
|
-
console.log('[Mockifyer] 📝 Creating test directory:', testDir);
|
|
817
695
|
fsToUse.mkdirSync(testDir, { recursive: true });
|
|
818
696
|
}
|
|
819
697
|
// Check if test file already exists
|
|
820
698
|
if (fsToUse.existsSync(absoluteTestPath)) {
|
|
821
|
-
console.log('[Mockifyer] 📝 Test file already exists, checking if test needs to be appended...');
|
|
822
699
|
// Extract test info to check if test already exists
|
|
823
700
|
const testInfo = this.testGenerator.analyzeMock(mockData, 'fetch');
|
|
824
701
|
const testName = this.generateTestNameFromInfo(testInfo);
|
|
825
702
|
// Check if test already exists
|
|
826
703
|
const existingContent = fsToUse.readFileSync(absoluteTestPath, 'utf-8');
|
|
827
704
|
if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
|
|
828
|
-
console.log(`[Mockifyer] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
|
|
829
705
|
return;
|
|
830
706
|
}
|
|
831
707
|
// Extract test code without imports and describe wrapper
|
|
@@ -835,21 +711,17 @@ class MockifyerClass {
|
|
|
835
711
|
const newTest = testMatch[0];
|
|
836
712
|
const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
|
|
837
713
|
fsToUse.writeFileSync(absoluteTestPath, updatedContent);
|
|
838
|
-
console.log(`[Mockifyer] ✅ Appended test to existing file: ${absoluteTestPath}`);
|
|
839
714
|
}
|
|
840
715
|
}
|
|
841
716
|
else {
|
|
842
717
|
// Create new test file
|
|
843
|
-
console.log('[Mockifyer] 📝 Creating new test file...');
|
|
844
718
|
fsToUse.writeFileSync(absoluteTestPath, testCode);
|
|
845
|
-
console.log(`[Mockifyer] ✅ Generated test: ${absoluteTestPath}`);
|
|
846
|
-
console.log(`[Mockifyer] ✅ Test file size: ${fsToUse.statSync(absoluteTestPath).size} bytes`);
|
|
847
719
|
}
|
|
848
720
|
}
|
|
849
721
|
catch (error) {
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
722
|
+
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error generating test:', error);
|
|
723
|
+
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error stack:', error?.stack);
|
|
724
|
+
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error message:', error?.message);
|
|
853
725
|
// Don't throw - test generation failure shouldn't break mock saving
|
|
854
726
|
}
|
|
855
727
|
}
|
|
@@ -935,17 +807,13 @@ class MockifyerClass {
|
|
|
935
807
|
await this.databaseProvider.clearAll();
|
|
936
808
|
}
|
|
937
809
|
else {
|
|
938
|
-
|
|
810
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
|
|
939
811
|
}
|
|
940
812
|
}
|
|
941
813
|
}
|
|
942
814
|
function setupMockifyer(config) {
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
recordMode: config.recordMode,
|
|
946
|
-
mockDataPath: config.mockDataPath,
|
|
947
|
-
databaseProvider: config.databaseProvider?.type
|
|
948
|
-
}, null, 2));
|
|
815
|
+
// Initialize logger with config level (default to 'info' if not specified)
|
|
816
|
+
(0, mockifyer_core_2.setLogLevel)(config.logging || 'info');
|
|
949
817
|
// Set environment variables for Metro middleware to read test generation config
|
|
950
818
|
// This allows Metro middleware (which runs in Node.js) to generate tests
|
|
951
819
|
// when Hybrid Provider saves mocks via Metro endpoint
|
|
@@ -972,10 +840,6 @@ function setupMockifyer(config) {
|
|
|
972
840
|
}
|
|
973
841
|
(0, mockifyer_core_1.initializeDateManipulation)(config);
|
|
974
842
|
(0, mockifyer_core_1.initializeScenario)(config);
|
|
975
|
-
console.log('[Mockifyer-Fetch] 🚀 After initializeScenario - config:', JSON.stringify({
|
|
976
|
-
generateTests: config.generateTests,
|
|
977
|
-
recordMode: config.recordMode
|
|
978
|
-
}, null, 2));
|
|
979
843
|
const mockifyer = new MockifyerClass(config);
|
|
980
844
|
const httpClient = mockifyer.getHTTPClient();
|
|
981
845
|
// Always store original fetch (even if not patching global)
|
|
@@ -1056,17 +920,6 @@ function setupMockifyer(config) {
|
|
|
1056
920
|
responseHeaders.set(key, String(value));
|
|
1057
921
|
}
|
|
1058
922
|
});
|
|
1059
|
-
// Debug: Verify x-mockifyer header is present
|
|
1060
|
-
if (response.headers['x-mockifyer']) {
|
|
1061
|
-
console.log('[Mockifyer-Fetch] ✅ x-mockifyer header found in response:', response.headers['x-mockifyer']);
|
|
1062
|
-
}
|
|
1063
|
-
else {
|
|
1064
|
-
console.warn('[Mockifyer-Fetch] ⚠️ x-mockifyer header NOT found in response.headers');
|
|
1065
|
-
console.warn('[Mockifyer-Fetch] Available headers:', Object.keys(response.headers));
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
else {
|
|
1069
|
-
console.warn('[Mockifyer-Fetch] ⚠️ response.headers is undefined/null');
|
|
1070
923
|
}
|
|
1071
924
|
const responseBody = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
|
|
1072
925
|
return new Response(responseBody, {
|
package/dist/metro-config.d.ts
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
*
|
|
4
4
|
* This helper configures Metro to stub Node.js built-in modules that aren't
|
|
5
5
|
* available in React Native, allowing Mockifyer to bundle successfully.
|
|
6
|
+
* Optionally sets up sync middleware for Hybrid Provider.
|
|
6
7
|
*
|
|
7
|
-
* @example
|
|
8
|
+
* @example Basic usage (fs stubbing only):
|
|
8
9
|
* ```javascript
|
|
9
10
|
* const { getDefaultConfig } = require('expo/metro-config');
|
|
10
11
|
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
@@ -12,7 +13,38 @@
|
|
|
12
13
|
* const config = getDefaultConfig(__dirname);
|
|
13
14
|
* module.exports = configureMetroForMockifyer(config);
|
|
14
15
|
* ```
|
|
16
|
+
*
|
|
17
|
+
* @example With sync middleware (for Hybrid Provider):
|
|
18
|
+
* ```javascript
|
|
19
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
20
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
21
|
+
*
|
|
22
|
+
* const config = getDefaultConfig(__dirname);
|
|
23
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
24
|
+
* syncMiddleware: {
|
|
25
|
+
* projectRoot: __dirname,
|
|
26
|
+
* mockDataPath: './mock-data',
|
|
27
|
+
* },
|
|
28
|
+
* });
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
|
|
32
|
+
* ```javascript
|
|
33
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
34
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
35
|
+
*
|
|
36
|
+
* const config = getDefaultConfig(__dirname);
|
|
37
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
38
|
+
* autoSync: {
|
|
39
|
+
* enabled: true,
|
|
40
|
+
* intervalMs: 5000,
|
|
41
|
+
* projectRoot: __dirname,
|
|
42
|
+
* mockDataPath: './mock-data',
|
|
43
|
+
* },
|
|
44
|
+
* });
|
|
45
|
+
* ```
|
|
15
46
|
*/
|
|
47
|
+
import type { MetroSyncMiddlewareOptions } from './metro-sync-middleware';
|
|
16
48
|
export interface MetroConfig {
|
|
17
49
|
resolver?: {
|
|
18
50
|
resolveRequest?: (context: any, moduleName: string, platform: string | null) => {
|
|
@@ -27,18 +59,37 @@ export interface MetroConfig {
|
|
|
27
59
|
server?: any;
|
|
28
60
|
[key: string]: any;
|
|
29
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Options for configuring Metro for Mockifyer
|
|
64
|
+
*/
|
|
65
|
+
export interface ConfigureMetroOptions {
|
|
66
|
+
/** Sync middleware options - if provided, sets up Hybrid Provider sync */
|
|
67
|
+
syncMiddleware?: MetroSyncMiddlewareOptions;
|
|
68
|
+
/** Auto-sync options - Required when using ExpoFileSystem Provider to sync files from device to project folder for code search. Not needed with Hybrid Provider (uses instant HTTP sync). */
|
|
69
|
+
autoSync?: {
|
|
70
|
+
/** Enable auto-sync (default: false). Set to true if using ExpoFileSystem Provider and want files in project folder for code search */
|
|
71
|
+
enabled?: boolean;
|
|
72
|
+
/** Sync interval in milliseconds (default: 5000) */
|
|
73
|
+
intervalMs?: number;
|
|
74
|
+
/** Project root directory (default: process.cwd()) */
|
|
75
|
+
projectRoot?: string;
|
|
76
|
+
/** Mock data path (default: 'mock-data') */
|
|
77
|
+
mockDataPath?: string;
|
|
78
|
+
};
|
|
79
|
+
}
|
|
30
80
|
/**
|
|
31
81
|
* Configure Metro bundler for Mockifyer
|
|
32
82
|
*
|
|
33
|
-
* This function
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
83
|
+
* This function:
|
|
84
|
+
* 1. Adds resolver configuration to stub Node.js built-in modules (fs, path, assert, util)
|
|
85
|
+
* 2. Optionally sets up sync middleware for Hybrid Provider (if syncMiddleware options provided)
|
|
86
|
+
* 3. Optionally sets up auto-sync polling (if autoSync options provided - needed for ExpoFileSystem Provider, not needed with Hybrid Provider)
|
|
37
87
|
*
|
|
38
88
|
* @param config - Existing Metro config (e.g., from getDefaultConfig)
|
|
39
|
-
* @
|
|
89
|
+
* @param options - Optional configuration including sync middleware setup
|
|
90
|
+
* @returns Metro config with Mockifyer configuration merged in
|
|
40
91
|
*
|
|
41
|
-
* @example
|
|
92
|
+
* @example Basic usage (fs stubbing only):
|
|
42
93
|
* ```javascript
|
|
43
94
|
* const { getDefaultConfig } = require('expo/metro-config');
|
|
44
95
|
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
@@ -46,5 +97,35 @@ export interface MetroConfig {
|
|
|
46
97
|
* const config = getDefaultConfig(__dirname);
|
|
47
98
|
* module.exports = configureMetroForMockifyer(config);
|
|
48
99
|
* ```
|
|
100
|
+
*
|
|
101
|
+
* @example With sync middleware (for Hybrid Provider):
|
|
102
|
+
* ```javascript
|
|
103
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
104
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
105
|
+
*
|
|
106
|
+
* const config = getDefaultConfig(__dirname);
|
|
107
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
108
|
+
* syncMiddleware: {
|
|
109
|
+
* projectRoot: __dirname,
|
|
110
|
+
* mockDataPath: './mock-data',
|
|
111
|
+
* },
|
|
112
|
+
* });
|
|
113
|
+
* ```
|
|
114
|
+
*
|
|
115
|
+
* @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
|
|
116
|
+
* ```javascript
|
|
117
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
118
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
119
|
+
*
|
|
120
|
+
* const config = getDefaultConfig(__dirname);
|
|
121
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
122
|
+
* autoSync: {
|
|
123
|
+
* enabled: true,
|
|
124
|
+
* intervalMs: 5000,
|
|
125
|
+
* projectRoot: __dirname,
|
|
126
|
+
* mockDataPath: './mock-data',
|
|
127
|
+
* },
|
|
128
|
+
* });
|
|
129
|
+
* ```
|
|
49
130
|
*/
|
|
50
|
-
export declare function configureMetroForMockifyer(config: MetroConfig): MetroConfig;
|
|
131
|
+
export declare function configureMetroForMockifyer(config: MetroConfig, options?: ConfigureMetroOptions): MetroConfig;
|