@sgedda/mockifyer-fetch 1.7.0
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 +97 -0
- package/dist/clients/fetch-client.d.ts +13 -0
- package/dist/clients/fetch-client.js +75 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +1106 -0
- package/dist/metro-config.d.ts +50 -0
- package/dist/metro-config.js +90 -0
- package/dist/metro-sync-middleware.d.ts +57 -0
- package/dist/metro-sync-middleware.js +483 -0
- package/dist/react-native.d.ts +44 -0
- package/dist/react-native.js +140 -0
- package/dist/test-generation-hook.d.ts +30 -0
- package/dist/test-generation-hook.js +138 -0
- package/metro-polyfills/empty-module.js +5 -0
- package/package.json +57 -0
- package/src/clients/fetch-client.ts +87 -0
- package/src/index.ts +1271 -0
- package/src/metro-config.ts +115 -0
- package/src/metro-sync-middleware.ts +560 -0
- package/src/react-native.ts +184 -0
- package/src/test-generation-hook.ts +146 -0
- package/tsconfig.json +19 -0
package/METRO_CONFIG.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Metro Configuration for React Native
|
|
2
|
+
|
|
3
|
+
Mockifyer requires Metro bundler configuration to stub Node.js built-in modules that aren't available in React Native.
|
|
4
|
+
|
|
5
|
+
## Quick Setup
|
|
6
|
+
|
|
7
|
+
Use the provided helper function to configure Metro automatically:
|
|
8
|
+
|
|
9
|
+
```javascript
|
|
10
|
+
// metro.config.js
|
|
11
|
+
const { getDefaultConfig } = require('expo/metro-config');
|
|
12
|
+
const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
13
|
+
|
|
14
|
+
const config = getDefaultConfig(__dirname);
|
|
15
|
+
module.exports = configureMetroForMockifyer(config);
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Manual Setup
|
|
19
|
+
|
|
20
|
+
If you prefer manual configuration or need more control:
|
|
21
|
+
|
|
22
|
+
```javascript
|
|
23
|
+
// metro.config.js
|
|
24
|
+
const { getDefaultConfig } = require('expo/metro-config');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
|
|
27
|
+
const config = getDefaultConfig(__dirname);
|
|
28
|
+
|
|
29
|
+
// Stub Node.js built-in modules
|
|
30
|
+
// fs, path: Used by FilesystemProvider
|
|
31
|
+
// assert, util: Used by @sinonjs/fake-timers (optional dependency)
|
|
32
|
+
const nodeBuiltins = ['fs', 'path', 'assert', 'util'];
|
|
33
|
+
const defaultResolver = config.resolver.resolveRequest;
|
|
34
|
+
|
|
35
|
+
config.resolver.resolveRequest = (context, moduleName, platform) => {
|
|
36
|
+
if (nodeBuiltins.includes(moduleName)) {
|
|
37
|
+
return {
|
|
38
|
+
filePath: require.resolve('@sgedda/mockifyer-fetch/metro-polyfills/empty-module'),
|
|
39
|
+
type: 'sourceFile',
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (defaultResolver) {
|
|
44
|
+
return defaultResolver(context, moduleName, platform);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return context.resolveRequest(context, moduleName, platform);
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
module.exports = config;
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Why This Is Needed
|
|
54
|
+
|
|
55
|
+
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
|
+
|
|
57
|
+
## Modules Stubbed
|
|
58
|
+
|
|
59
|
+
- `fs` - Used by FilesystemProvider (not used in React Native - use ExpoFileSystemProvider instead)
|
|
60
|
+
- `path` - Used by FilesystemProvider
|
|
61
|
+
- `assert` - Used by @sinonjs/fake-timers (optional dependency for date manipulation)
|
|
62
|
+
- `util` - Used by @sinonjs/fake-timers (optional dependency for date manipulation)
|
|
63
|
+
|
|
64
|
+
## Bundle Size Impact
|
|
65
|
+
|
|
66
|
+
- **Metro config code**: 0 bytes (runs at build time, not bundled)
|
|
67
|
+
- **Empty module stubs**: ~10-30 bytes total (only if referenced)
|
|
68
|
+
- **Total impact**: Negligible (~30 bytes)
|
|
69
|
+
|
|
70
|
+
## Troubleshooting
|
|
71
|
+
|
|
72
|
+
### Error: "Unable to resolve module 'fs'"
|
|
73
|
+
|
|
74
|
+
This means the Metro config isn't set up correctly. Use the `configureMetroForMockifyer` helper or add manual stubbing as shown above.
|
|
75
|
+
|
|
76
|
+
### Error: "Cannot find module '@sgedda/mockifyer-fetch/metro-polyfills/empty-module'"
|
|
77
|
+
|
|
78
|
+
Make sure you've installed `@sgedda/mockifyer-fetch` and the package exports are configured correctly. Try:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
npm install @sgedda/mockifyer-fetch
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Custom Metro Config Already Exists
|
|
85
|
+
|
|
86
|
+
The helper function merges with your existing config. If you have custom resolvers, they'll be preserved:
|
|
87
|
+
|
|
88
|
+
```javascript
|
|
89
|
+
const config = getDefaultConfig(__dirname);
|
|
90
|
+
|
|
91
|
+
// Your custom config
|
|
92
|
+
config.resolver.extraNodeModules = { /* ... */ };
|
|
93
|
+
|
|
94
|
+
// Add Mockifyer config (preserves your custom resolver)
|
|
95
|
+
module.exports = configureMetroForMockifyer(config);
|
|
96
|
+
```
|
|
97
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { BaseHTTPClient } from '@sgedda/mockifyer-core';
|
|
2
|
+
import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
|
|
3
|
+
export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
4
|
+
private baseUrl?;
|
|
5
|
+
private defaultHeaders;
|
|
6
|
+
constructor(config?: {
|
|
7
|
+
baseUrl?: string;
|
|
8
|
+
defaultHeaders?: Record<string, string>;
|
|
9
|
+
});
|
|
10
|
+
protected performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>>;
|
|
11
|
+
protected getDefaultHeaders(): Record<string, string>;
|
|
12
|
+
protected getDefaultConfig(): Record<string, any>;
|
|
13
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FetchHTTPClient = void 0;
|
|
4
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
5
|
+
class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
6
|
+
constructor(config) {
|
|
7
|
+
super();
|
|
8
|
+
this.baseUrl = config?.baseUrl;
|
|
9
|
+
this.defaultHeaders = config?.defaultHeaders || {};
|
|
10
|
+
}
|
|
11
|
+
async performRequest(config) {
|
|
12
|
+
// Check if this is a mock response (set by Mockifyer interceptor)
|
|
13
|
+
if (config.__mockResponse) {
|
|
14
|
+
return config.__mockResponse;
|
|
15
|
+
}
|
|
16
|
+
let url = this.baseUrl ? new URL(config.url || '', this.baseUrl).toString() : config.url;
|
|
17
|
+
if (!url) {
|
|
18
|
+
throw new Error('URL is required');
|
|
19
|
+
}
|
|
20
|
+
// Handle query parameters (params) - append them to the URL
|
|
21
|
+
if (config.params && Object.keys(config.params).length > 0) {
|
|
22
|
+
try {
|
|
23
|
+
const urlObj = new URL(url);
|
|
24
|
+
Object.entries(config.params).forEach(([key, value]) => {
|
|
25
|
+
if (value !== undefined && value !== null) {
|
|
26
|
+
urlObj.searchParams.append(key, String(value));
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
url = urlObj.toString();
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
console.error('[FetchHTTPClient] Error adding params to URL:', error);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const headers = new Headers({
|
|
37
|
+
...this.defaultHeaders,
|
|
38
|
+
...config.headers
|
|
39
|
+
});
|
|
40
|
+
const requestConfig = {
|
|
41
|
+
method: config.method || 'GET',
|
|
42
|
+
headers,
|
|
43
|
+
body: config.data ? JSON.stringify(config.data) : undefined
|
|
44
|
+
};
|
|
45
|
+
// Use original fetch if available (when global fetch is patched), otherwise use global fetch
|
|
46
|
+
// CRITICAL: Always use _originalFetch if available to prevent infinite loops
|
|
47
|
+
const fetchFn = this._originalFetch || fetch;
|
|
48
|
+
if (!this._originalFetch) {
|
|
49
|
+
console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
|
|
50
|
+
}
|
|
51
|
+
const response = await fetchFn(url, requestConfig);
|
|
52
|
+
const data = await response.json();
|
|
53
|
+
// Convert response Headers to Record<string, string>
|
|
54
|
+
const responseHeaders = {};
|
|
55
|
+
response.headers.forEach((value, key) => {
|
|
56
|
+
responseHeaders[key] = value;
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
data,
|
|
60
|
+
status: response.status,
|
|
61
|
+
statusText: response.statusText,
|
|
62
|
+
headers: responseHeaders,
|
|
63
|
+
config
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
getDefaultHeaders() {
|
|
67
|
+
return this.defaultHeaders;
|
|
68
|
+
}
|
|
69
|
+
getDefaultConfig() {
|
|
70
|
+
return {
|
|
71
|
+
baseUrl: this.baseUrl
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
exports.FetchHTTPClient = FetchHTTPClient;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { MockifyerConfig, HTTPClient } from '@sgedda/mockifyer-core';
|
|
2
|
+
export interface MockifyerInstance extends HTTPClient {
|
|
3
|
+
reloadMockData: () => Promise<void>;
|
|
4
|
+
clearStaleCacheEntries: () => number;
|
|
5
|
+
clearAllMocks: () => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export declare function setupMockifyer(config: MockifyerConfig): MockifyerInstance;
|
|
8
|
+
export * from '@sgedda/mockifyer-core';
|
|
9
|
+
export * from './react-native';
|