vitest-native 0.2.1 → 0.4.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/CHANGELOG.md +86 -0
- package/README.md +268 -9
- package/dist/chunk-CZWwpsFl.cjs +43 -0
- package/dist/helpers.cjs +10 -0
- package/dist/helpers.d.cts +7 -1
- package/dist/helpers.d.mts +7 -1
- package/dist/helpers.mjs +10 -1
- package/dist/{index-CJqS-y_M.d.cts → index-CJIhukN_.d.mts} +58 -4
- package/dist/{index-h4vpIkQO.d.mts → index-DEB7OFaJ.d.cts} +60 -2
- package/dist/index.cjs +296 -35
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +292 -33
- package/dist/jest-compat/interop.mjs +30 -0
- package/dist/jest-compat/jest-globals.d.mts +3 -0
- package/dist/jest-compat/jest-globals.mjs +9 -0
- package/dist/jest-compat/noop.d.mts +3 -0
- package/dist/jest-compat/noop.mjs +7 -0
- package/dist/jest-compat/setup.d.mts +3 -0
- package/dist/jest-compat/setup.mjs +41 -0
- package/dist/jest-compat.cjs +109 -0
- package/dist/jest-compat.d.cts +38 -0
- package/dist/jest-compat.d.mts +38 -0
- package/dist/jest-compat.mjs +104 -0
- package/dist/matchers.cjs +69 -0
- package/dist/matchers.d.cts +51 -0
- package/dist/matchers.d.mts +51 -0
- package/dist/matchers.mjs +66 -0
- package/dist/native/boundary.mjs +225 -0
- package/dist/native/globals.mjs +112 -0
- package/dist/native/hooks.mjs +85 -0
- package/dist/native/loader.mjs +123 -0
- package/dist/native/match.mjs +9 -0
- package/dist/native/reset.mjs +170 -0
- package/dist/native/resolve.mjs +22 -0
- package/dist/native/runner.mjs +18 -0
- package/dist/native/setup.mjs +134 -0
- package/dist/native/transform.mjs +79 -0
- package/dist/native/worker.mjs +96 -0
- package/dist/pool-B4mWN3N5.cjs +60 -0
- package/dist/pool-oPTZiSXU.mjs +58 -0
- package/dist/{preset-map-Bt4dXkZO.cjs → preset-map-C3jxnkiX.cjs} +6 -1
- package/dist/{preset-map-D224CC5w.mjs → preset-map-OJm5IWuL.mjs} +6 -1
- package/dist/{presets-9Y4ssfiH.cjs → presets-2I68Ipyl.cjs} +768 -122
- package/dist/{presets-CWH0gtM0.mjs → presets-DOGXQzYT.mjs} +732 -87
- package/dist/presets.cjs +5 -1
- package/dist/presets.d.cts +2 -2
- package/dist/presets.d.mts +2 -2
- package/dist/presets.mjs +2 -2
- package/dist/setup.cjs +903 -121
- package/dist/setup.mjs +899 -118
- package/docs/migrating-from-jest.md +123 -0
- package/docs/migrating-from-vitest-react-native.md +109 -0
- package/package.json +67 -8
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import { Mock } from "vitest";
|
|
2
2
|
|
|
3
|
-
//#region \0rolldown/runtime.js
|
|
4
|
-
//#endregion
|
|
5
3
|
//#region src/types.d.ts
|
|
6
4
|
/** Static methods available on the Image component mock. */
|
|
7
5
|
interface ImageStatic {
|
|
@@ -207,6 +205,17 @@ interface Preset {
|
|
|
207
205
|
interface VitestNativeOptions {
|
|
208
206
|
/** Target platform. Default: 'ios' */
|
|
209
207
|
platform?: "ios" | "android";
|
|
208
|
+
/**
|
|
209
|
+
* Test engine.
|
|
210
|
+
* - 'mock' — pure-JS reimplementation of React Native (fastest, lower fidelity).
|
|
211
|
+
* - 'native' — runs real React Native JS, mocking only the native boundary
|
|
212
|
+
* (Jest-level fidelity).
|
|
213
|
+
* - 'auto' — picks automatically. Currently resolves to 'mock'; when
|
|
214
|
+
* '@react-native/babel-preset' is present it recommends 'native'
|
|
215
|
+
* (becomes the default in v1).
|
|
216
|
+
* Default: 'auto'.
|
|
217
|
+
*/
|
|
218
|
+
engine?: "auto" | "mock" | "native";
|
|
210
219
|
/**
|
|
211
220
|
* Built-in third-party library presets. When provided, only these presets
|
|
212
221
|
* are used. When omitted, vitest-native auto-detects installed packages
|
|
@@ -239,6 +248,39 @@ interface VitestNativeOptions {
|
|
|
239
248
|
diagnostics?: boolean;
|
|
240
249
|
/** Additional asset file extensions to stub (e.g. ['.lottie', '.m4b']) */
|
|
241
250
|
assetExts?: string[];
|
|
251
|
+
/**
|
|
252
|
+
* `engine: 'native'` only. Names of additional node_modules packages whose
|
|
253
|
+
* source the native engine should transform (Flow/TS/JSX stripped) as it
|
|
254
|
+
* loads them. By default only `react-native` / `@react-native` are
|
|
255
|
+
* transformed; third-party RN libraries that ship untranspiled source
|
|
256
|
+
* (e.g. `react-native-reanimated`, `react-native-safe-area-context`) need to
|
|
257
|
+
* be listed here, analogous to Jest's `transformIgnorePatterns` allowlist.
|
|
258
|
+
*
|
|
259
|
+
* @example
|
|
260
|
+
* ```ts
|
|
261
|
+
* reactNative({ engine: 'native', transform: ['react-native-reanimated'] })
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
transform?: string[];
|
|
265
|
+
/**
|
|
266
|
+
* `engine: 'native'` only. **Experimental.** Run tests in persistent
|
|
267
|
+
* RN-hot workers: React Native's module graph loads once per worker and
|
|
268
|
+
* stays resident across test files, while each file still gets a fresh
|
|
269
|
+
* Vitest module runner (per-file isolation of your app/test modules).
|
|
270
|
+
* Uses a custom Vitest pool + worker entry + runner; requires Vitest >= 4.
|
|
271
|
+
*
|
|
272
|
+
* Pass an object to tune worker recycling (self-defense against suites that
|
|
273
|
+
* leak process-wide resources the per-file reset can't reclaim):
|
|
274
|
+
* - `recycleAfterFiles`: retire a worker after it has run N test files.
|
|
275
|
+
* - `memoryLimit`: retire a worker when its JS heap (bytes) after a test
|
|
276
|
+
* file meets or exceeds this value.
|
|
277
|
+
*
|
|
278
|
+
* Default: false (each file runs in a fresh worker; RN reloads per file).
|
|
279
|
+
*/
|
|
280
|
+
hotRuntime?: boolean | {
|
|
281
|
+
recycleAfterFiles?: number;
|
|
282
|
+
memoryLimit?: number;
|
|
283
|
+
};
|
|
242
284
|
}
|
|
243
285
|
//#endregion
|
|
244
286
|
//#region src/presets/reanimated.d.ts
|
|
@@ -261,8 +303,20 @@ declare function screens(): Preset;
|
|
|
261
303
|
//#endregion
|
|
262
304
|
//#region src/presets/expo.d.ts
|
|
263
305
|
declare function expo(): Preset;
|
|
306
|
+
//#endregion
|
|
307
|
+
//#region src/presets/device-info.d.ts
|
|
308
|
+
declare function deviceInfo(): Preset;
|
|
309
|
+
//#endregion
|
|
310
|
+
//#region src/presets/mmkv.d.ts
|
|
311
|
+
declare function mmkv(): Preset;
|
|
312
|
+
//#endregion
|
|
313
|
+
//#region src/presets/svg.d.ts
|
|
314
|
+
declare function svg(): Preset;
|
|
315
|
+
//#endregion
|
|
316
|
+
//#region src/presets/webview.d.ts
|
|
317
|
+
declare function webview(): Preset;
|
|
264
318
|
declare namespace index_d_exports {
|
|
265
|
-
export { asyncStorage, expo, gestureHandler, navigation, reanimated, safeAreaContext, screens };
|
|
319
|
+
export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, webview };
|
|
266
320
|
}
|
|
267
321
|
//#endregion
|
|
268
|
-
export {
|
|
322
|
+
export { deviceInfo as a, asyncStorage as c, gestureHandler as d, reanimated as f, VitestNativeOptions as h, mmkv as i, navigation as l, ReactNativeMock as m, webview as n, expo as o, Preset as p, svg as r, screens as s, index_d_exports as t, safeAreaContext as u };
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { Mock } from "vitest";
|
|
2
2
|
|
|
3
|
+
//#region \0rolldown/runtime.js
|
|
4
|
+
//#endregion
|
|
3
5
|
//#region src/types.d.ts
|
|
4
6
|
/** Static methods available on the Image component mock. */
|
|
5
7
|
interface ImageStatic {
|
|
@@ -205,6 +207,17 @@ interface Preset {
|
|
|
205
207
|
interface VitestNativeOptions {
|
|
206
208
|
/** Target platform. Default: 'ios' */
|
|
207
209
|
platform?: "ios" | "android";
|
|
210
|
+
/**
|
|
211
|
+
* Test engine.
|
|
212
|
+
* - 'mock' — pure-JS reimplementation of React Native (fastest, lower fidelity).
|
|
213
|
+
* - 'native' — runs real React Native JS, mocking only the native boundary
|
|
214
|
+
* (Jest-level fidelity).
|
|
215
|
+
* - 'auto' — picks automatically. Currently resolves to 'mock'; when
|
|
216
|
+
* '@react-native/babel-preset' is present it recommends 'native'
|
|
217
|
+
* (becomes the default in v1).
|
|
218
|
+
* Default: 'auto'.
|
|
219
|
+
*/
|
|
220
|
+
engine?: "auto" | "mock" | "native";
|
|
208
221
|
/**
|
|
209
222
|
* Built-in third-party library presets. When provided, only these presets
|
|
210
223
|
* are used. When omitted, vitest-native auto-detects installed packages
|
|
@@ -237,6 +250,39 @@ interface VitestNativeOptions {
|
|
|
237
250
|
diagnostics?: boolean;
|
|
238
251
|
/** Additional asset file extensions to stub (e.g. ['.lottie', '.m4b']) */
|
|
239
252
|
assetExts?: string[];
|
|
253
|
+
/**
|
|
254
|
+
* `engine: 'native'` only. Names of additional node_modules packages whose
|
|
255
|
+
* source the native engine should transform (Flow/TS/JSX stripped) as it
|
|
256
|
+
* loads them. By default only `react-native` / `@react-native` are
|
|
257
|
+
* transformed; third-party RN libraries that ship untranspiled source
|
|
258
|
+
* (e.g. `react-native-reanimated`, `react-native-safe-area-context`) need to
|
|
259
|
+
* be listed here, analogous to Jest's `transformIgnorePatterns` allowlist.
|
|
260
|
+
*
|
|
261
|
+
* @example
|
|
262
|
+
* ```ts
|
|
263
|
+
* reactNative({ engine: 'native', transform: ['react-native-reanimated'] })
|
|
264
|
+
* ```
|
|
265
|
+
*/
|
|
266
|
+
transform?: string[];
|
|
267
|
+
/**
|
|
268
|
+
* `engine: 'native'` only. **Experimental.** Run tests in persistent
|
|
269
|
+
* RN-hot workers: React Native's module graph loads once per worker and
|
|
270
|
+
* stays resident across test files, while each file still gets a fresh
|
|
271
|
+
* Vitest module runner (per-file isolation of your app/test modules).
|
|
272
|
+
* Uses a custom Vitest pool + worker entry + runner; requires Vitest >= 4.
|
|
273
|
+
*
|
|
274
|
+
* Pass an object to tune worker recycling (self-defense against suites that
|
|
275
|
+
* leak process-wide resources the per-file reset can't reclaim):
|
|
276
|
+
* - `recycleAfterFiles`: retire a worker after it has run N test files.
|
|
277
|
+
* - `memoryLimit`: retire a worker when its JS heap (bytes) after a test
|
|
278
|
+
* file meets or exceeds this value.
|
|
279
|
+
*
|
|
280
|
+
* Default: false (each file runs in a fresh worker; RN reloads per file).
|
|
281
|
+
*/
|
|
282
|
+
hotRuntime?: boolean | {
|
|
283
|
+
recycleAfterFiles?: number;
|
|
284
|
+
memoryLimit?: number;
|
|
285
|
+
};
|
|
240
286
|
}
|
|
241
287
|
//#endregion
|
|
242
288
|
//#region src/presets/reanimated.d.ts
|
|
@@ -259,8 +305,20 @@ declare function screens(): Preset;
|
|
|
259
305
|
//#endregion
|
|
260
306
|
//#region src/presets/expo.d.ts
|
|
261
307
|
declare function expo(): Preset;
|
|
308
|
+
//#endregion
|
|
309
|
+
//#region src/presets/device-info.d.ts
|
|
310
|
+
declare function deviceInfo(): Preset;
|
|
311
|
+
//#endregion
|
|
312
|
+
//#region src/presets/mmkv.d.ts
|
|
313
|
+
declare function mmkv(): Preset;
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region src/presets/svg.d.ts
|
|
316
|
+
declare function svg(): Preset;
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/presets/webview.d.ts
|
|
319
|
+
declare function webview(): Preset;
|
|
262
320
|
declare namespace index_d_exports {
|
|
263
|
-
export { asyncStorage, expo, gestureHandler, navigation, reanimated, safeAreaContext, screens };
|
|
321
|
+
export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, webview };
|
|
264
322
|
}
|
|
265
323
|
//#endregion
|
|
266
|
-
export {
|
|
324
|
+
export { deviceInfo as a, asyncStorage as c, gestureHandler as d, reanimated as f, VitestNativeOptions as h, mmkv as i, navigation as l, ReactNativeMock as m, webview as n, expo as o, Preset as p, svg as r, screens as s, index_d_exports as t, safeAreaContext as u };
|
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
3
|
-
const require_preset_map = require("./preset-map-
|
|
2
|
+
const require_chunk = require("./chunk-CZWwpsFl.cjs");
|
|
3
|
+
const require_preset_map = require("./preset-map-C3jxnkiX.cjs");
|
|
4
|
+
const require_presets = require("./presets-2I68Ipyl.cjs");
|
|
4
5
|
let node_url = require("node:url");
|
|
5
6
|
let node_path = require("node:path");
|
|
6
|
-
node_path =
|
|
7
|
+
node_path = require_chunk.__toESM(node_path);
|
|
7
8
|
let node_fs = require("node:fs");
|
|
8
|
-
node_fs =
|
|
9
|
+
node_fs = require_chunk.__toESM(node_fs);
|
|
9
10
|
let node_module = require("node:module");
|
|
11
|
+
let flow_remove_types = require("flow-remove-types");
|
|
12
|
+
flow_remove_types = require_chunk.__toESM(flow_remove_types);
|
|
10
13
|
//#region src/resolve.ts
|
|
11
14
|
const PLATFORM_EXTENSIONS_IOS = [
|
|
12
15
|
".ios.tsx",
|
|
@@ -40,6 +43,158 @@ function getPlatformExtensions(platform) {
|
|
|
40
43
|
return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
|
|
41
44
|
}
|
|
42
45
|
//#endregion
|
|
46
|
+
//#region src/validate.ts
|
|
47
|
+
const KNOWN_OPTIONS = [
|
|
48
|
+
"platform",
|
|
49
|
+
"presets",
|
|
50
|
+
"mocks",
|
|
51
|
+
"diagnostics",
|
|
52
|
+
"assetExts",
|
|
53
|
+
"engine",
|
|
54
|
+
"transform",
|
|
55
|
+
"hotRuntime"
|
|
56
|
+
];
|
|
57
|
+
function satisfiesMinimum(version, minimum) {
|
|
58
|
+
const parse = (v) => v.replace(/^[^0-9]*/, "").split(".").map(Number);
|
|
59
|
+
const [aMaj, aMin = 0, aPat = 0] = parse(version);
|
|
60
|
+
const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
|
|
61
|
+
if (aMaj !== bMaj) return aMaj > bMaj;
|
|
62
|
+
if (aMin !== bMin) return aMin > bMin;
|
|
63
|
+
return aPat >= bPat;
|
|
64
|
+
}
|
|
65
|
+
function validatePeerDependency(pkgName, minimumVersion, projectRoot) {
|
|
66
|
+
const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
|
|
67
|
+
try {
|
|
68
|
+
const { version } = req(req.resolve(`${pkgName}/package.json`));
|
|
69
|
+
if (!satisfiesMinimum(version, minimumVersion)) return `vitest-native requires ${pkgName} >= ${minimumVersion}, but found ${version}. Please upgrade.`;
|
|
70
|
+
return null;
|
|
71
|
+
} catch {
|
|
72
|
+
return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function warnUnknownOptions(options) {
|
|
76
|
+
for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
|
|
77
|
+
const suggestion = findClosest(key, KNOWN_OPTIONS);
|
|
78
|
+
const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
|
|
79
|
+
console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function findClosest(input, candidates) {
|
|
83
|
+
let best = null;
|
|
84
|
+
let bestDist = Infinity;
|
|
85
|
+
for (const c of candidates) {
|
|
86
|
+
const d = levenshtein(input.toLowerCase(), c.toLowerCase());
|
|
87
|
+
if (d < bestDist && d <= 3) {
|
|
88
|
+
bestDist = d;
|
|
89
|
+
best = c;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return best;
|
|
93
|
+
}
|
|
94
|
+
function levenshtein(a, b) {
|
|
95
|
+
const m = a.length;
|
|
96
|
+
const n = b.length;
|
|
97
|
+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
|
98
|
+
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
99
|
+
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
100
|
+
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
|
|
101
|
+
return dp[m][n];
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/native/apply.ts
|
|
105
|
+
/**
|
|
106
|
+
* Vite/Vitest config fragment for the native engine. RN is externalized so it
|
|
107
|
+
* loads through Node's single CJS graph, where the native setup file's hooks
|
|
108
|
+
* Flow-strip it and mock the native boundary.
|
|
109
|
+
*/
|
|
110
|
+
/** Escape a package name for use inside a RegExp character-delimited path match. */
|
|
111
|
+
function escapeRe(s) {
|
|
112
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
113
|
+
}
|
|
114
|
+
function nativeEngineConfig(setupFilePath, env, transformPkgs = [], hot) {
|
|
115
|
+
const extraExternal = transformPkgs.map((p) => new RegExp(`[\\\\/]${escapeRe(p)}[\\\\/]`));
|
|
116
|
+
const fullEnv = { ...env };
|
|
117
|
+
if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
|
|
118
|
+
return {
|
|
119
|
+
esbuild: { jsx: "automatic" },
|
|
120
|
+
resolve: {
|
|
121
|
+
conditions: ["react-native"],
|
|
122
|
+
extensions: [
|
|
123
|
+
".ios.tsx",
|
|
124
|
+
".ios.ts",
|
|
125
|
+
".ios.js",
|
|
126
|
+
".native.tsx",
|
|
127
|
+
".native.ts",
|
|
128
|
+
".native.js",
|
|
129
|
+
".tsx",
|
|
130
|
+
".ts",
|
|
131
|
+
".jsx",
|
|
132
|
+
".js"
|
|
133
|
+
],
|
|
134
|
+
dedupe: [
|
|
135
|
+
"react",
|
|
136
|
+
"react-test-renderer",
|
|
137
|
+
"react-is"
|
|
138
|
+
]
|
|
139
|
+
},
|
|
140
|
+
test: {
|
|
141
|
+
setupFiles: [setupFilePath],
|
|
142
|
+
env: fullEnv,
|
|
143
|
+
...hot ? {
|
|
144
|
+
pool: hot.pool,
|
|
145
|
+
isolate: false,
|
|
146
|
+
runner: hot.runnerPath
|
|
147
|
+
} : { pool: "threads" },
|
|
148
|
+
server: { deps: { external: [
|
|
149
|
+
/[\\/]react-native[\\/]/,
|
|
150
|
+
/[\\/]@react-native[\\/]/,
|
|
151
|
+
...extraExternal
|
|
152
|
+
] } }
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/** Can this project run the native engine? (Both transform deps resolvable.) */
|
|
157
|
+
function isNativeCapable(projectRoot) {
|
|
158
|
+
try {
|
|
159
|
+
const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
|
|
160
|
+
req.resolve("@react-native/babel-preset");
|
|
161
|
+
req.resolve("@babel/core");
|
|
162
|
+
return true;
|
|
163
|
+
} catch {
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** Resolve the concrete engine for a run. Pure; never throws. */
|
|
168
|
+
function detectEngine(requested, projectRoot, opts) {
|
|
169
|
+
const nativeAvailable = isNativeCapable(projectRoot);
|
|
170
|
+
if (requested === "native") return {
|
|
171
|
+
engine: "native",
|
|
172
|
+
nativeAvailable,
|
|
173
|
+
notice: null
|
|
174
|
+
};
|
|
175
|
+
if (requested === "mock") return {
|
|
176
|
+
engine: "mock",
|
|
177
|
+
nativeAvailable,
|
|
178
|
+
notice: null
|
|
179
|
+
};
|
|
180
|
+
const prefersNative = opts?.autoPrefersNative ?? true;
|
|
181
|
+
if (prefersNative && nativeAvailable) return {
|
|
182
|
+
engine: "native",
|
|
183
|
+
nativeAvailable,
|
|
184
|
+
notice: null
|
|
185
|
+
};
|
|
186
|
+
if (prefersNative) return {
|
|
187
|
+
engine: "mock",
|
|
188
|
+
nativeAvailable: false,
|
|
189
|
+
notice: "[vitest-native] @react-native/babel-preset not found — using the mock engine. Install it (and @babel/core) to run real React Native, or set engine:'mock' to silence this."
|
|
190
|
+
};
|
|
191
|
+
return {
|
|
192
|
+
engine: "mock",
|
|
193
|
+
nativeAvailable,
|
|
194
|
+
notice: null
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
//#endregion
|
|
43
198
|
//#region src/plugin.ts
|
|
44
199
|
const DEFAULT_ASSET_EXTS = [
|
|
45
200
|
"png",
|
|
@@ -68,40 +223,55 @@ const DEFAULT_ASSET_EXTS = [
|
|
|
68
223
|
function stripFsPrefix(id) {
|
|
69
224
|
return id.startsWith("/@fs/") ? id.slice(4) : id;
|
|
70
225
|
}
|
|
71
|
-
/**
|
|
72
|
-
* Check if a package is installed from the consumer's project root,
|
|
73
|
-
* not from the plugin's own node_modules. This is critical for monorepos
|
|
74
|
-
* and non-hoisted layouts (pnpm strict, yarn PnP).
|
|
75
|
-
*/
|
|
76
|
-
function isPackageInstalled(packageName, projectRoot) {
|
|
77
|
-
try {
|
|
78
|
-
(0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json")).resolve(packageName);
|
|
79
|
-
return true;
|
|
80
|
-
} catch {
|
|
81
|
-
return false;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
226
|
async function autoDetectPresets(diagnostics, projectRoot) {
|
|
85
227
|
const detected = [];
|
|
86
228
|
const presetFactories = await Promise.resolve().then(() => require("./presets.cjs"));
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
229
|
+
const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
|
|
230
|
+
for (const [pkgName, exportName] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) {
|
|
231
|
+
let installed = false;
|
|
232
|
+
try {
|
|
233
|
+
req.resolve(pkgName);
|
|
234
|
+
installed = true;
|
|
235
|
+
} catch {}
|
|
236
|
+
if (installed) {
|
|
237
|
+
const factory = presetFactories[exportName];
|
|
238
|
+
if (typeof factory === "function") {
|
|
239
|
+
detected.push(factory());
|
|
240
|
+
if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
|
|
241
|
+
}
|
|
242
|
+
} else if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
|
|
93
243
|
}
|
|
94
244
|
return detected;
|
|
95
245
|
}
|
|
246
|
+
/**
|
|
247
|
+
* Synchronously resolve the export-names of presets whose package is installed.
|
|
248
|
+
* Used by the native-engine config path (which can't await the factory imports)
|
|
249
|
+
* to tell the native setup file which preset mocks to build. Returns deduped
|
|
250
|
+
* preset names (e.g. ["reanimated", "navigation"]).
|
|
251
|
+
*/
|
|
252
|
+
function autoDetectPresetNames(projectRoot, diagnostics) {
|
|
253
|
+
const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
|
|
254
|
+
const names = /* @__PURE__ */ new Set();
|
|
255
|
+
for (const [pkgName, exportName] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) try {
|
|
256
|
+
req.resolve(pkgName);
|
|
257
|
+
names.add(exportName);
|
|
258
|
+
if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
|
|
259
|
+
} catch {
|
|
260
|
+
if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
|
|
261
|
+
}
|
|
262
|
+
return [...names];
|
|
263
|
+
}
|
|
96
264
|
async function resolveOptions(options = {}, projectRoot) {
|
|
97
265
|
const platform = options.platform ?? "ios";
|
|
98
266
|
const diagnostics = options.diagnostics ?? false;
|
|
267
|
+
const engine = options.engine === "native" ? "native" : "mock";
|
|
99
268
|
const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
|
|
100
269
|
let presets;
|
|
101
270
|
if (options.presets) presets = options.presets;
|
|
102
271
|
else presets = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
|
|
103
272
|
return {
|
|
104
273
|
platform,
|
|
274
|
+
engine,
|
|
105
275
|
diagnostics,
|
|
106
276
|
extensions: getPlatformExtensions(platform),
|
|
107
277
|
presets,
|
|
@@ -215,35 +385,69 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
|
|
|
215
385
|
*/
|
|
216
386
|
function reactNative(options) {
|
|
217
387
|
if (options?.mocks && containsFunctions(options.mocks)) throw new Error("[vitest-native] The \"mocks\" option contains function values, which cannot be transferred to Vitest worker processes. Only JSON-serializable values (strings, numbers, booleans, plain objects, arrays) are supported.\n\nFor function-based mock overrides, use vi.mock() in a setup file:\n\n // vitest.setup.ts\n import { vi } from 'vitest';\n vi.mock('react-native', async (importOriginal) => {\n const actual = await importOriginal();\n return { ...actual, Alert: { alert: vi.fn() } };\n });");
|
|
388
|
+
if (options) warnUnknownOptions(options);
|
|
218
389
|
let resolved;
|
|
219
390
|
const presetModules = /* @__PURE__ */ new Map();
|
|
220
391
|
const presetExportNames = /* @__PURE__ */ new Map();
|
|
221
392
|
let assetPattern;
|
|
393
|
+
const resolveCache = /* @__PURE__ */ new Map();
|
|
394
|
+
const virtualCodeCache = /* @__PURE__ */ new Map();
|
|
222
395
|
const thisDir = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
|
|
223
396
|
let setupFilePath = node_path.default.resolve(thisDir, "setup.mjs");
|
|
224
397
|
if (!node_fs.default.existsSync(setupFilePath)) {
|
|
225
398
|
const srcPath = node_path.default.resolve(thisDir, "setup.ts");
|
|
226
399
|
if (node_fs.default.existsSync(srcPath)) setupFilePath = srcPath;
|
|
227
400
|
}
|
|
401
|
+
const nativeSetupPath = node_path.default.resolve(thisDir, "native/setup.mjs");
|
|
402
|
+
const nativeWorkerPath = node_path.default.resolve(thisDir, "native/worker.mjs");
|
|
403
|
+
const nativeRunnerPath = node_path.default.resolve(thisDir, "native/runner.mjs");
|
|
228
404
|
const platform = options?.platform ?? "ios";
|
|
229
405
|
const diagnostics = options?.diagnostics ?? false;
|
|
406
|
+
const requestedEngine = options?.engine ?? "auto";
|
|
407
|
+
const transformPkgs = (options?.transform ?? []).filter((p) => typeof p === "string" && p.length > 0);
|
|
408
|
+
const hotRuntimeOpt = options?.hotRuntime ?? false;
|
|
409
|
+
const hotRuntime = hotRuntimeOpt !== false;
|
|
410
|
+
const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
|
|
411
|
+
let engine = requestedEngine === "native" ? "native" : "mock";
|
|
230
412
|
const extensions = getPlatformExtensions(platform);
|
|
231
413
|
return {
|
|
232
414
|
name: "vitest-native",
|
|
233
415
|
enforce: "pre",
|
|
234
|
-
config(userConfig, _env) {
|
|
416
|
+
async config(userConfig, _env) {
|
|
235
417
|
const resolvedRoot = userConfig.root ? node_path.default.resolve(userConfig.root) : process.cwd();
|
|
418
|
+
const decision = detectEngine(requestedEngine, resolvedRoot);
|
|
419
|
+
engine = decision.engine;
|
|
420
|
+
if (decision.notice) console.log(decision.notice);
|
|
236
421
|
const env = {
|
|
237
422
|
VITEST_NATIVE_PLATFORM: platform,
|
|
238
423
|
VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
|
|
239
424
|
VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
|
|
240
425
|
};
|
|
426
|
+
if (engine === "native") {
|
|
427
|
+
const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
|
|
428
|
+
if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
|
|
429
|
+
return nativeEngineConfig(nativeSetupPath, env, transformPkgs, hotRuntime ? {
|
|
430
|
+
pool: (await Promise.resolve().then(() => require("./pool-B4mWN3N5.cjs"))).nativePool({
|
|
431
|
+
workerEntry: nativeWorkerPath,
|
|
432
|
+
recycleAfterFiles: hotRecycle.recycleAfterFiles,
|
|
433
|
+
memoryLimit: hotRecycle.memoryLimit
|
|
434
|
+
}),
|
|
435
|
+
runnerPath: nativeRunnerPath
|
|
436
|
+
} : void 0);
|
|
437
|
+
}
|
|
438
|
+
if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
|
|
241
439
|
if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
|
|
242
440
|
if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
|
|
243
441
|
return {
|
|
442
|
+
esbuild: { jsx: "automatic" },
|
|
244
443
|
resolve: {
|
|
245
444
|
extensions,
|
|
246
|
-
conditions: ["react-native"]
|
|
445
|
+
conditions: ["react-native"],
|
|
446
|
+
dedupe: [
|
|
447
|
+
"react",
|
|
448
|
+
"react-test-renderer",
|
|
449
|
+
"react-is"
|
|
450
|
+
]
|
|
247
451
|
},
|
|
248
452
|
test: {
|
|
249
453
|
setupFiles: [setupFilePath],
|
|
@@ -252,7 +456,27 @@ function reactNative(options) {
|
|
|
252
456
|
};
|
|
253
457
|
},
|
|
254
458
|
async configResolved(config) {
|
|
459
|
+
for (const { name, range } of [
|
|
460
|
+
{
|
|
461
|
+
name: "vitest",
|
|
462
|
+
range: "4.0.0"
|
|
463
|
+
},
|
|
464
|
+
{
|
|
465
|
+
name: "vite",
|
|
466
|
+
range: "5.0.0"
|
|
467
|
+
},
|
|
468
|
+
{
|
|
469
|
+
name: "react",
|
|
470
|
+
range: "18.0.0"
|
|
471
|
+
}
|
|
472
|
+
]) {
|
|
473
|
+
const error = validatePeerDependency(name, range, config.root);
|
|
474
|
+
if (error) console.error(`[vitest-native] ${error}`);
|
|
475
|
+
}
|
|
476
|
+
const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root);
|
|
477
|
+
if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
|
|
255
478
|
resolved = await resolveOptions(options, config.root);
|
|
479
|
+
resolved.engine = engine;
|
|
256
480
|
for (const preset of resolved.presets) for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
|
|
257
481
|
presetModules.set(moduleName, presetModule.factory);
|
|
258
482
|
presetExportNames.set(moduleName, presetModule.exports);
|
|
@@ -260,40 +484,77 @@ function reactNative(options) {
|
|
|
260
484
|
assetPattern = new RegExp(`\\.(${resolved.assetExts.join("|")})$`);
|
|
261
485
|
},
|
|
262
486
|
resolveId(source, importer) {
|
|
487
|
+
if (engine === "native") {
|
|
488
|
+
if (presetModules.has(source)) return `\0virtual:preset:${source}`;
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
263
491
|
if (source === "react-native") return "\0virtual:react-native";
|
|
264
492
|
if (source.startsWith("react-native/")) return `\0virtual:rn-subpath:${source}`;
|
|
265
493
|
if (presetModules.has(source)) return `\0virtual:preset:${source}`;
|
|
266
494
|
if (importer && importer.includes("node_modules") && source.startsWith(".") && !node_path.default.extname(source)) {
|
|
495
|
+
const cacheKey = `${importer}\0${source}`;
|
|
496
|
+
const cached = resolveCache.get(cacheKey);
|
|
497
|
+
if (cached !== void 0) return cached;
|
|
267
498
|
const importerDir = node_path.default.dirname(importer);
|
|
268
499
|
const absolute = node_path.default.resolve(importerDir, source);
|
|
269
500
|
for (const ext of extensions) {
|
|
270
501
|
const candidate = absolute + ext;
|
|
271
|
-
if (node_fs.default.existsSync(candidate))
|
|
502
|
+
if (node_fs.default.existsSync(candidate)) {
|
|
503
|
+
resolveCache.set(cacheKey, candidate);
|
|
504
|
+
return candidate;
|
|
505
|
+
}
|
|
272
506
|
}
|
|
273
507
|
for (const ext of extensions) {
|
|
274
508
|
const candidate = node_path.default.join(absolute, `index${ext}`);
|
|
275
|
-
if (node_fs.default.existsSync(candidate))
|
|
509
|
+
if (node_fs.default.existsSync(candidate)) {
|
|
510
|
+
resolveCache.set(cacheKey, candidate);
|
|
511
|
+
return candidate;
|
|
512
|
+
}
|
|
276
513
|
}
|
|
514
|
+
resolveCache.set(cacheKey, void 0);
|
|
277
515
|
}
|
|
278
516
|
},
|
|
279
517
|
load(id) {
|
|
280
|
-
if (id === "\0virtual:react-native") return "export default {};";
|
|
281
|
-
if (id.startsWith("\0virtual:rn-subpath:")) return [
|
|
282
|
-
`const _rn = globalThis.__vitest_native_mock || {};`,
|
|
283
|
-
...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
|
|
284
|
-
`export default _rn;`
|
|
285
|
-
].join("\n");
|
|
286
518
|
if (id.startsWith("\0virtual:preset:")) {
|
|
519
|
+
const cached = virtualCodeCache.get(id);
|
|
520
|
+
if (cached) return cached;
|
|
287
521
|
const moduleName = id.slice(16);
|
|
288
522
|
const exportNames = presetExportNames.get(moduleName) || [];
|
|
289
|
-
|
|
523
|
+
const code = [
|
|
290
524
|
`const _m = (globalThis.__vitest_native_preset_mocks || {})['${moduleName}'] || {};`,
|
|
291
525
|
...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
|
|
292
|
-
`export default _m;`
|
|
526
|
+
`export default ('default' in _m ? _m['default'] : _m);`
|
|
293
527
|
].join("\n");
|
|
528
|
+
virtualCodeCache.set(id, code);
|
|
529
|
+
return code;
|
|
530
|
+
}
|
|
531
|
+
if (engine === "native") return void 0;
|
|
532
|
+
if (id === "\0virtual:react-native") return "export default {};";
|
|
533
|
+
if (id.startsWith("\0virtual:rn-subpath:")) {
|
|
534
|
+
let code = virtualCodeCache.get("\0rn-subpath");
|
|
535
|
+
if (!code) {
|
|
536
|
+
code = [
|
|
537
|
+
`const _rn = globalThis.__vitest_native_mock || {};`,
|
|
538
|
+
...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
|
|
539
|
+
`export default _rn;`
|
|
540
|
+
].join("\n");
|
|
541
|
+
virtualCodeCache.set("\0rn-subpath", code);
|
|
542
|
+
}
|
|
543
|
+
return code;
|
|
294
544
|
}
|
|
295
545
|
const fsPath = stripFsPrefix(id);
|
|
296
546
|
if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
|
|
547
|
+
},
|
|
548
|
+
transform(code, id) {
|
|
549
|
+
if (engine === "native") return void 0;
|
|
550
|
+
if (!id.includes("node_modules")) return void 0;
|
|
551
|
+
if (!id.includes("react-native") || !id.endsWith(".js")) return void 0;
|
|
552
|
+
if (!code.includes("@flow")) return void 0;
|
|
553
|
+
const stripped = (0, flow_remove_types.default)(code, { all: true });
|
|
554
|
+
return {
|
|
555
|
+
code: stripped.toString(),
|
|
556
|
+
map: stripped.generateMap()
|
|
557
|
+
};
|
|
297
558
|
}
|
|
298
559
|
};
|
|
299
560
|
}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { h as VitestNativeOptions, m as ReactNativeMock, p as Preset, t as index_d_exports } from "./index-DEB7OFaJ.cjs";
|
|
2
2
|
import { Plugin } from "vite";
|
|
3
3
|
|
|
4
4
|
//#region src/plugin.d.ts
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { h as VitestNativeOptions, m as ReactNativeMock, p as Preset, t as index_d_exports } from "./index-CJIhukN_.mjs";
|
|
2
2
|
import { Plugin } from "vite";
|
|
3
3
|
|
|
4
4
|
//#region src/plugin.d.ts
|