vitest-native 0.4.1 → 0.6.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 +98 -1
- package/README.md +270 -180
- package/dist/helpers.cjs +13 -0
- package/dist/helpers.mjs +13 -0
- package/dist/{index-DEB7OFaJ.d.cts → index-DGNLmGjq.d.mts} +19 -12
- package/dist/{index-CJIhukN_.d.mts → index-Dr3WvKWI.d.cts} +21 -10
- package/dist/index.cjs +106 -39
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +103 -36
- package/dist/jest-compat.cjs +1 -1
- package/dist/native/boundary.mjs +82 -32
- package/dist/native/globals.mjs +1 -0
- package/dist/native/hooks.mjs +35 -7
- package/dist/native/loader.mjs +18 -5
- package/dist/native/reset.mjs +79 -43
- package/dist/native/resolve.mjs +25 -7
- package/dist/native/runner.mjs +13 -2
- package/dist/native/setup.mjs +95 -4
- package/dist/native/transform.mjs +15 -9
- package/dist/native/worker.mjs +20 -3
- package/dist/{pool-oPTZiSXU.mjs → pool-B7LBfcMQ.mjs} +10 -1
- package/dist/{pool-B4mWN3N5.cjs → pool-p54QV1dQ.cjs} +11 -2
- package/dist/{preset-map-OJm5IWuL.mjs → preset-map-C1UwEald.mjs} +3 -1
- package/dist/{preset-map-C3jxnkiX.cjs → preset-map-CNBOeqAu.cjs} +3 -1
- package/dist/{presets-2I68Ipyl.cjs → presets-BPVVlfI2.cjs} +93 -23
- package/dist/{presets-DOGXQzYT.mjs → presets-DVLDrPC-.mjs} +86 -22
- package/dist/presets.cjs +2 -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 +71 -13
- package/dist/setup.mjs +69 -11
- package/docs/migrating-from-jest.md +6 -4
- package/docs/migrating-from-vitest-react-native.md +6 -3
- package/docs/release-readiness.md +52 -0
- package/package.json +31 -20
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as AUTO_DETECT_PRESETS } from "./preset-map-
|
|
2
|
-
import { t as presets_exports } from "./presets-
|
|
1
|
+
import { t as AUTO_DETECT_PRESETS } from "./preset-map-C1UwEald.mjs";
|
|
2
|
+
import { t as presets_exports } from "./presets-DVLDrPC-.mjs";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import path from "node:path";
|
|
@@ -49,6 +49,34 @@ const KNOWN_OPTIONS = [
|
|
|
49
49
|
"transform",
|
|
50
50
|
"hotRuntime"
|
|
51
51
|
];
|
|
52
|
+
const KNOWN_HOT_RUNTIME_OPTIONS = [
|
|
53
|
+
"recycleAfterFiles",
|
|
54
|
+
"memoryLimit",
|
|
55
|
+
"preserveGlobals"
|
|
56
|
+
];
|
|
57
|
+
function assertStringArray(value, option) {
|
|
58
|
+
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new TypeError(`[vitest-native] "${option}" must be an array of non-empty strings.`);
|
|
59
|
+
}
|
|
60
|
+
function assertNonNegativeInteger(value, option) {
|
|
61
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new TypeError(`[vitest-native] "${option}" must be a non-negative safe integer.`);
|
|
62
|
+
}
|
|
63
|
+
function validateOptions(options) {
|
|
64
|
+
if (options.engine !== void 0 && options.engine !== "auto" && options.engine !== "mock" && options.engine !== "native") throw new TypeError(`[vitest-native] "engine" must be "auto", "mock", or "native".`);
|
|
65
|
+
if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new TypeError(`[vitest-native] "platform" must be "ios" or "android".`);
|
|
66
|
+
if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new TypeError(`[vitest-native] "diagnostics" must be a boolean.`);
|
|
67
|
+
if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
|
|
68
|
+
if (options.transform !== void 0) assertStringArray(options.transform, "transform");
|
|
69
|
+
if (options.presets !== void 0 && !Array.isArray(options.presets)) throw new TypeError(`[vitest-native] "presets" must be an array.`);
|
|
70
|
+
if (options.mocks !== void 0 && (options.mocks === null || Array.isArray(options.mocks) || typeof options.mocks !== "object")) throw new TypeError(`[vitest-native] "mocks" must be a plain object.`);
|
|
71
|
+
const hotRuntime = options.hotRuntime;
|
|
72
|
+
if (hotRuntime === void 0 || typeof hotRuntime === "boolean") return;
|
|
73
|
+
if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new TypeError(`[vitest-native] "hotRuntime" must be a boolean or an options object.`);
|
|
74
|
+
const hotOptions = hotRuntime;
|
|
75
|
+
for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) throw new TypeError(`[vitest-native] Unknown hotRuntime option "${key}".`);
|
|
76
|
+
if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
|
|
77
|
+
if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
|
|
78
|
+
if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
|
|
79
|
+
}
|
|
52
80
|
function satisfiesMinimum(version, minimum) {
|
|
53
81
|
const parse = (v) => v.replace(/^[^0-9]*/, "").split(".").map(Number);
|
|
54
82
|
const [aMaj, aMin = 0, aPat = 0] = parse(version);
|
|
@@ -57,11 +85,14 @@ function satisfiesMinimum(version, minimum) {
|
|
|
57
85
|
if (aMin !== bMin) return aMin > bMin;
|
|
58
86
|
return aPat >= bPat;
|
|
59
87
|
}
|
|
60
|
-
function validatePeerDependency(pkgName, minimumVersion, projectRoot) {
|
|
88
|
+
function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
|
|
61
89
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
62
90
|
try {
|
|
63
91
|
const { version } = req(req.resolve(`${pkgName}/package.json`));
|
|
64
|
-
|
|
92
|
+
const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
|
|
93
|
+
const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
|
|
94
|
+
if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
|
|
95
|
+
if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
|
|
65
96
|
return null;
|
|
66
97
|
} catch {
|
|
67
98
|
return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
|
|
@@ -106,29 +137,19 @@ function levenshtein(a, b) {
|
|
|
106
137
|
function escapeRe(s) {
|
|
107
138
|
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
108
139
|
}
|
|
109
|
-
function nativeEngineConfig(setupFilePath, env, transformPkgs = [], hot) {
|
|
140
|
+
function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }) {
|
|
110
141
|
const extraExternal = transformPkgs.map((p) => new RegExp(`[\\\\/]${escapeRe(p)}[\\\\/]`));
|
|
111
142
|
const fullEnv = { ...env };
|
|
112
143
|
if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
|
|
113
144
|
return {
|
|
114
|
-
|
|
145
|
+
...jsxTransform,
|
|
115
146
|
resolve: {
|
|
116
147
|
conditions: ["react-native"],
|
|
117
|
-
extensions
|
|
118
|
-
".ios.tsx",
|
|
119
|
-
".ios.ts",
|
|
120
|
-
".ios.js",
|
|
121
|
-
".native.tsx",
|
|
122
|
-
".native.ts",
|
|
123
|
-
".native.js",
|
|
124
|
-
".tsx",
|
|
125
|
-
".ts",
|
|
126
|
-
".jsx",
|
|
127
|
-
".js"
|
|
128
|
-
],
|
|
148
|
+
extensions,
|
|
129
149
|
dedupe: [
|
|
130
150
|
"react",
|
|
131
151
|
"react-test-renderer",
|
|
152
|
+
"test-renderer",
|
|
132
153
|
"react-is"
|
|
133
154
|
]
|
|
134
155
|
},
|
|
@@ -220,6 +241,7 @@ function stripFsPrefix(id) {
|
|
|
220
241
|
}
|
|
221
242
|
async function autoDetectPresets(diagnostics, projectRoot) {
|
|
222
243
|
const detected = [];
|
|
244
|
+
const enabled = /* @__PURE__ */ new Set();
|
|
223
245
|
const presetFactories = await import("./presets.mjs");
|
|
224
246
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
225
247
|
for (const [pkgName, exportName] of Object.entries(AUTO_DETECT_PRESETS)) {
|
|
@@ -229,15 +251,39 @@ async function autoDetectPresets(diagnostics, projectRoot) {
|
|
|
229
251
|
installed = true;
|
|
230
252
|
} catch {}
|
|
231
253
|
if (installed) {
|
|
254
|
+
if (enabled.has(exportName)) continue;
|
|
232
255
|
const factory = presetFactories[exportName];
|
|
233
256
|
if (typeof factory === "function") {
|
|
234
257
|
detected.push(factory());
|
|
258
|
+
enabled.add(exportName);
|
|
235
259
|
if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
|
|
236
260
|
}
|
|
237
261
|
} else if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
|
|
238
262
|
}
|
|
239
263
|
return detected;
|
|
240
264
|
}
|
|
265
|
+
function resolvePackageVersion(packageName, projectRoot) {
|
|
266
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
267
|
+
try {
|
|
268
|
+
return req(`${packageName}/package.json`).version ?? null;
|
|
269
|
+
} catch {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function getJsxTransformConfig(projectRoot) {
|
|
274
|
+
const viteVersion = resolvePackageVersion("vite", projectRoot);
|
|
275
|
+
return Number(viteVersion?.split(".")[0]) >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
|
|
279
|
+
* `esbuild.jsx` before Vite 8 and `oxc.jsx` from Vite 8 onward. The runtime
|
|
280
|
+
* version check above guarantees that only the matching shape is returned,
|
|
281
|
+
* but a build against any single Vite major cannot type the other major's
|
|
282
|
+
* valid config. Keep that unavoidable assertion at this compatibility edge.
|
|
283
|
+
*/
|
|
284
|
+
function asCompatibleViteConfig(config) {
|
|
285
|
+
return config;
|
|
286
|
+
}
|
|
241
287
|
/**
|
|
242
288
|
* Synchronously resolve the export-names of presets whose package is installed.
|
|
243
289
|
* Used by the native-engine config path (which can't await the factory imports)
|
|
@@ -379,8 +425,11 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
|
|
|
379
425
|
* React Native code in a Node/JSDOM environment.
|
|
380
426
|
*/
|
|
381
427
|
function reactNative(options) {
|
|
428
|
+
if (options) {
|
|
429
|
+
validateOptions(options);
|
|
430
|
+
warnUnknownOptions(options);
|
|
431
|
+
}
|
|
382
432
|
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 });");
|
|
383
|
-
if (options) warnUnknownOptions(options);
|
|
384
433
|
let resolved;
|
|
385
434
|
const presetModules = /* @__PURE__ */ new Map();
|
|
386
435
|
const presetExportNames = /* @__PURE__ */ new Map();
|
|
@@ -410,6 +459,7 @@ function reactNative(options) {
|
|
|
410
459
|
enforce: "pre",
|
|
411
460
|
async config(userConfig, _env) {
|
|
412
461
|
const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
|
|
462
|
+
const jsxTransform = getJsxTransformConfig(resolvedRoot);
|
|
413
463
|
const decision = detectEngine(requestedEngine, resolvedRoot);
|
|
414
464
|
engine = decision.engine;
|
|
415
465
|
if (decision.notice) console.log(decision.notice);
|
|
@@ -418,29 +468,36 @@ function reactNative(options) {
|
|
|
418
468
|
VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
|
|
419
469
|
VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
|
|
420
470
|
};
|
|
471
|
+
const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
|
|
472
|
+
if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
|
|
473
|
+
env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify([...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))]);
|
|
474
|
+
if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
|
|
421
475
|
if (engine === "native") {
|
|
476
|
+
if (options?.mocks && Object.keys(options.mocks).length > 0) throw new Error("[vitest-native] The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
|
|
422
477
|
const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
|
|
423
478
|
if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
|
|
424
|
-
return nativeEngineConfig(nativeSetupPath, env, transformPkgs, hotRuntime ? {
|
|
425
|
-
pool: (await import("./pool-
|
|
479
|
+
return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hotRuntime ? {
|
|
480
|
+
pool: (await import("./pool-B7LBfcMQ.mjs")).nativePool({
|
|
426
481
|
workerEntry: nativeWorkerPath,
|
|
427
482
|
recycleAfterFiles: hotRecycle.recycleAfterFiles,
|
|
428
|
-
memoryLimit: hotRecycle.memoryLimit
|
|
483
|
+
memoryLimit: hotRecycle.memoryLimit,
|
|
484
|
+
diagnostics
|
|
429
485
|
}),
|
|
430
486
|
runnerPath: nativeRunnerPath
|
|
431
|
-
} : void 0);
|
|
487
|
+
} : void 0, jsxTransform));
|
|
432
488
|
}
|
|
433
489
|
if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
|
|
434
490
|
if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
|
|
435
491
|
if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
|
|
436
|
-
return {
|
|
437
|
-
|
|
492
|
+
return asCompatibleViteConfig({
|
|
493
|
+
...jsxTransform,
|
|
438
494
|
resolve: {
|
|
439
495
|
extensions,
|
|
440
496
|
conditions: ["react-native"],
|
|
441
497
|
dedupe: [
|
|
442
498
|
"react",
|
|
443
499
|
"react-test-renderer",
|
|
500
|
+
"test-renderer",
|
|
444
501
|
"react-is"
|
|
445
502
|
]
|
|
446
503
|
},
|
|
@@ -448,27 +505,37 @@ function reactNative(options) {
|
|
|
448
505
|
setupFiles: [setupFilePath],
|
|
449
506
|
env
|
|
450
507
|
}
|
|
451
|
-
};
|
|
508
|
+
});
|
|
452
509
|
},
|
|
453
510
|
async configResolved(config) {
|
|
454
|
-
|
|
511
|
+
const peers = [
|
|
455
512
|
{
|
|
456
513
|
name: "vitest",
|
|
457
|
-
|
|
514
|
+
minimum: "4.0.0",
|
|
515
|
+
maximumMajor: 5
|
|
458
516
|
},
|
|
459
517
|
{
|
|
460
518
|
name: "vite",
|
|
461
|
-
|
|
519
|
+
minimum: "6.4.2",
|
|
520
|
+
maximumMajor: 9,
|
|
521
|
+
minimumByMajor: {
|
|
522
|
+
6: "6.4.2",
|
|
523
|
+
7: "7.3.2",
|
|
524
|
+
8: "8.0.5"
|
|
525
|
+
}
|
|
462
526
|
},
|
|
463
527
|
{
|
|
464
528
|
name: "react",
|
|
465
|
-
|
|
529
|
+
minimum: "18.0.0"
|
|
466
530
|
}
|
|
467
|
-
]
|
|
468
|
-
|
|
469
|
-
|
|
531
|
+
];
|
|
532
|
+
const peerErrors = [];
|
|
533
|
+
for (const { name, minimum, maximumMajor, minimumByMajor } of peers) {
|
|
534
|
+
const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
|
|
535
|
+
if (error) peerErrors.push(error);
|
|
470
536
|
}
|
|
471
|
-
|
|
537
|
+
if (peerErrors.length > 0) throw new Error(`[vitest-native] Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
|
|
538
|
+
const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root, 15);
|
|
472
539
|
if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
|
|
473
540
|
resolved = await resolveOptions(options, config.root);
|
|
474
541
|
resolved.engine = engine;
|
|
@@ -523,6 +590,8 @@ function reactNative(options) {
|
|
|
523
590
|
virtualCodeCache.set(id, code);
|
|
524
591
|
return code;
|
|
525
592
|
}
|
|
593
|
+
const fsPath = stripFsPrefix(id);
|
|
594
|
+
if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
|
|
526
595
|
if (engine === "native") return void 0;
|
|
527
596
|
if (id === "\0virtual:react-native") return "export default {};";
|
|
528
597
|
if (id.startsWith("\0virtual:rn-subpath:")) {
|
|
@@ -537,8 +606,6 @@ function reactNative(options) {
|
|
|
537
606
|
}
|
|
538
607
|
return code;
|
|
539
608
|
}
|
|
540
|
-
const fsPath = stripFsPrefix(id);
|
|
541
|
-
if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
|
|
542
609
|
},
|
|
543
610
|
transform(code, id) {
|
|
544
611
|
if (engine === "native") return void 0;
|
package/dist/jest-compat.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_chunk = require("./chunk-CZWwpsFl.cjs");
|
|
3
3
|
let magic_string = require("magic-string");
|
|
4
|
-
magic_string = require_chunk.__toESM(magic_string);
|
|
4
|
+
magic_string = require_chunk.__toESM(magic_string, 1);
|
|
5
5
|
//#region src/jest-compat/transform.ts
|
|
6
6
|
const HOISTABLE = new Set([
|
|
7
7
|
"mock",
|
package/dist/native/boundary.mjs
CHANGED
|
@@ -3,27 +3,52 @@
|
|
|
3
3
|
// expressed as CJS source strings so both transform hooks (loader + require) can
|
|
4
4
|
// serve them identically. Mirrors react-native/jest/setup.js's mock set.
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
6
|
+
function parseVersion(version) {
|
|
7
|
+
const [major = 0, minor = 0, patch = 0] = String(version || "0.0.0")
|
|
8
|
+
.split(/[.-]/)
|
|
9
|
+
.map((part) => Number.parseInt(part, 10) || 0);
|
|
10
|
+
return { major, minor, patch };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function deviceConstants(platform, reactNativeVersion) {
|
|
14
|
+
const platformConstants =
|
|
15
|
+
platform === "android"
|
|
16
|
+
? {
|
|
17
|
+
isTesting: true,
|
|
18
|
+
reactNativeVersion,
|
|
19
|
+
Version: 34,
|
|
20
|
+
Release: "14",
|
|
21
|
+
Serial: "unknown",
|
|
22
|
+
Fingerprint: "vitest-native",
|
|
23
|
+
Model: "vitest-native",
|
|
24
|
+
uiMode: "normal",
|
|
25
|
+
Brand: "generic",
|
|
26
|
+
Manufacturer: "generic",
|
|
27
|
+
}
|
|
28
|
+
: {
|
|
29
|
+
forceTouchAvailable: false,
|
|
30
|
+
reactNativeVersion,
|
|
31
|
+
osVersion: "17.0",
|
|
32
|
+
systemName: "iOS",
|
|
33
|
+
interfaceIdiom: "phone",
|
|
34
|
+
isTesting: true,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
PlatformConstants: platformConstants,
|
|
39
|
+
DeviceInfo: {
|
|
40
|
+
Dimensions: {
|
|
41
|
+
window: { width: 390, height: 844, scale: 3, fontScale: 1 },
|
|
42
|
+
screen: { width: 390, height: 844, scale: 3, fontScale: 1 },
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
I18nManager: {
|
|
46
|
+
isRTL: false,
|
|
47
|
+
doLeftAndRightSwapInRTL: true,
|
|
48
|
+
localeIdentifier: "en_US",
|
|
19
49
|
},
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
isRTL: false,
|
|
23
|
-
doLeftAndRightSwapInRTL: true,
|
|
24
|
-
localeIdentifier: "en_US",
|
|
25
|
-
},
|
|
26
|
-
});
|
|
50
|
+
};
|
|
51
|
+
}
|
|
27
52
|
|
|
28
53
|
// A reusable mock-native-component factory, inlined into each source string that needs it.
|
|
29
54
|
//
|
|
@@ -71,8 +96,18 @@ const MOCK_NATIVE_COMPONENT = `
|
|
|
71
96
|
};
|
|
72
97
|
`;
|
|
73
98
|
|
|
74
|
-
|
|
75
|
-
const
|
|
99
|
+
function turboStubSource(platform, version) {
|
|
100
|
+
const constants = JSON.stringify(deviceConstants(platform, parseVersion(version)));
|
|
101
|
+
return `
|
|
102
|
+
const __C = ${constants};
|
|
103
|
+
const __moduleMocks = () => globalThis.__vitest_native_module_mocks || {};
|
|
104
|
+
const __boundaryState =
|
|
105
|
+
globalThis.__vitest_native_boundary_state ||
|
|
106
|
+
(globalThis.__vitest_native_boundary_state = Object.create(null));
|
|
107
|
+
const getBoundaryState = (name) =>
|
|
108
|
+
__boundaryState[name] || (__boundaryState[name] = Object.create(null));
|
|
109
|
+
const getModuleMock = (name) =>
|
|
110
|
+
Object.prototype.hasOwnProperty.call(__moduleMocks(), name) ? __moduleMocks()[name] : null;
|
|
76
111
|
// Native methods that return a Promise on the device (no callback arg). Without
|
|
77
112
|
// this, real RN code doing \`NativeModule.canOpenURL(url).then(...)\` would crash
|
|
78
113
|
// on \`undefined\`. Values are the no-native defaults.
|
|
@@ -94,7 +129,15 @@ const TURBO_STUB = `
|
|
|
94
129
|
const turboStub = (name) => new Proxy({}, {
|
|
95
130
|
get: (_t, p) => {
|
|
96
131
|
if (p === "getConstants") return () => (__C[name] || {});
|
|
97
|
-
if (p === "getColorScheme")
|
|
132
|
+
if (p === "getColorScheme") {
|
|
133
|
+
return () => getBoundaryState(name).colorScheme ?? "light";
|
|
134
|
+
}
|
|
135
|
+
if (p === "setColorScheme") {
|
|
136
|
+
return (colorScheme) => {
|
|
137
|
+
getBoundaryState(name).colorScheme =
|
|
138
|
+
colorScheme === "unspecified" || colorScheme == null ? "light" : colorScheme;
|
|
139
|
+
};
|
|
140
|
+
}
|
|
98
141
|
if (p === "addListener") return () => ({ remove: () => {} });
|
|
99
142
|
if (p === "removeListeners") return () => {};
|
|
100
143
|
return (...args) => {
|
|
@@ -114,17 +157,21 @@ const TURBO_STUB = `
|
|
|
114
157
|
},
|
|
115
158
|
});
|
|
116
159
|
`;
|
|
160
|
+
}
|
|
117
161
|
|
|
118
162
|
export const BOUNDARY_SOURCES = {
|
|
119
|
-
"Libraries/TurboModule/TurboModuleRegistry.js": `
|
|
120
|
-
${
|
|
121
|
-
exports.get = (n) => turboStub(n);
|
|
122
|
-
exports.getEnforcing = (n) => turboStub(n);
|
|
163
|
+
"Libraries/TurboModule/TurboModuleRegistry.js": (platform, version) => `
|
|
164
|
+
${turboStubSource(platform, version)}
|
|
165
|
+
exports.get = (n) => getModuleMock(n) || turboStub(n);
|
|
166
|
+
exports.getEnforcing = (n) => getModuleMock(n) || turboStub(n);
|
|
123
167
|
`,
|
|
124
|
-
"Libraries/BatchedBridge/NativeModules.js": `
|
|
125
|
-
${
|
|
168
|
+
"Libraries/BatchedBridge/NativeModules.js": (platform, version) => `
|
|
169
|
+
${turboStubSource(platform, version)}
|
|
126
170
|
module.exports = { __esModule: true, default: new Proxy({}, {
|
|
127
|
-
get: (_t, n) =>
|
|
171
|
+
get: (_t, n) => {
|
|
172
|
+
if (typeof n !== "string") return undefined;
|
|
173
|
+
return getModuleMock(n) || turboStub(n);
|
|
174
|
+
},
|
|
128
175
|
}) };
|
|
129
176
|
`,
|
|
130
177
|
"Libraries/NativeComponent/NativeComponentRegistry.js": `
|
|
@@ -217,9 +264,12 @@ export function isBoundary(normPath) {
|
|
|
217
264
|
}
|
|
218
265
|
|
|
219
266
|
/** Returns the CJS source for a boundary module, or null if not a boundary. */
|
|
220
|
-
export function boundarySourceFor(normPath) {
|
|
267
|
+
export function boundarySourceFor(normPath, platform = "ios", version = "0.0.0") {
|
|
221
268
|
for (const s of SUFFIXES) {
|
|
222
|
-
if (normPath.endsWith("/react-native/" + s))
|
|
269
|
+
if (normPath.endsWith("/react-native/" + s)) {
|
|
270
|
+
const source = BOUNDARY_SOURCES[s];
|
|
271
|
+
return typeof source === "function" ? source(platform, version) : source;
|
|
272
|
+
}
|
|
223
273
|
}
|
|
224
274
|
return null;
|
|
225
275
|
}
|
package/dist/native/globals.mjs
CHANGED
|
@@ -21,6 +21,7 @@ export function installGlobals() {
|
|
|
21
21
|
g.IS_REACT_ACT_ENVIRONMENT = true;
|
|
22
22
|
g.IS_REACT_NATIVE_TEST_ENVIRONMENT = true;
|
|
23
23
|
g.__fbBatchedBridgeConfig = { remoteModuleConfig: [], localModulesConfig: [] };
|
|
24
|
+
g.__vitest_native_module_mocks = g.__vitest_native_module_mocks || {};
|
|
24
25
|
|
|
25
26
|
installExpoGlobal(g);
|
|
26
27
|
}
|
package/dist/native/hooks.mjs
CHANGED
|
@@ -14,10 +14,34 @@ const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
|
|
|
14
14
|
// can be evaluated twice in one worker (once by the worker entry through Node's
|
|
15
15
|
// loader, once through Vitest's module runner when the setup file is inlined),
|
|
16
16
|
// and the hooks must still install exactly once per worker.
|
|
17
|
-
export function installRequireHooks(
|
|
17
|
+
export function installRequireHooks(
|
|
18
|
+
projectRoot,
|
|
19
|
+
transformPkgs = [],
|
|
20
|
+
platform = "ios",
|
|
21
|
+
reactNativeVersion = "0.0.0",
|
|
22
|
+
assetExts = [],
|
|
23
|
+
) {
|
|
18
24
|
if (globalThis.__vitest_native_require_hooks_installed) return;
|
|
19
25
|
globalThis.__vitest_native_require_hooks_installed = true;
|
|
20
26
|
|
|
27
|
+
// Asset requires (`require('./logo.png')`, `require('./Icon.ttf')`) reaching
|
|
28
|
+
// Node's CJS loader must be stubbed, not compiled — otherwise the binary falls
|
|
29
|
+
// through to the `.js` handler and throws "SyntaxError: Invalid or unexpected
|
|
30
|
+
// token". RN's packager and Jest's asset transform both stub these (incl.
|
|
31
|
+
// fonts); the Vite graph already does too, so we match it here (module.exports =
|
|
32
|
+
// basename string) for the Node path. (Font-loading libraries like
|
|
33
|
+
// @react-native-vector-icons are shadowed by their preset, so they never inspect
|
|
34
|
+
// the stubbed font require.)
|
|
35
|
+
const NON_ASSET = new Set([".js", ".cjs", ".mjs", ".ts", ".tsx", ".json", ".node"]);
|
|
36
|
+
for (const raw of assetExts) {
|
|
37
|
+
const ext = "." + String(raw).replace(/^\./, "");
|
|
38
|
+
if (NON_ASSET.has(ext) || Module._extensions[ext]) continue;
|
|
39
|
+
Module._extensions[ext] = function (mod, filename) {
|
|
40
|
+
const basename = filename.replace(/\\/g, "/").split("/").pop() || filename;
|
|
41
|
+
mod.exports = basename;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
21
45
|
// Configured third-party packages to also transform (Flow/TS/JSX stripped).
|
|
22
46
|
const isExtra = buildPkgMatcher(transformPkgs);
|
|
23
47
|
|
|
@@ -42,11 +66,14 @@ export function installRequireHooks(projectRoot, transformPkgs = []) {
|
|
|
42
66
|
if (
|
|
43
67
|
parent &&
|
|
44
68
|
parent.filename &&
|
|
45
|
-
RN_PATH.test(parent.filename) &&
|
|
69
|
+
(RN_PATH.test(parent.filename) || isExtra(parent.filename)) &&
|
|
46
70
|
request.startsWith(".") &&
|
|
47
71
|
!path.extname(request)
|
|
48
72
|
) {
|
|
49
|
-
const hit = resolvePlatformFile(
|
|
73
|
+
const hit = resolvePlatformFile(
|
|
74
|
+
path.resolve(path.dirname(parent.filename), request),
|
|
75
|
+
platform,
|
|
76
|
+
);
|
|
50
77
|
if (hit) return hit;
|
|
51
78
|
}
|
|
52
79
|
return origResolve.call(this, request, parent, ...rest);
|
|
@@ -55,16 +82,17 @@ export function installRequireHooks(projectRoot, transformPkgs = []) {
|
|
|
55
82
|
const origJs = Module._extensions[".js"];
|
|
56
83
|
Module._extensions[".js"] = function (mod, filename) {
|
|
57
84
|
const norm = filename.replace(/\\/g, "/");
|
|
58
|
-
const boundary = boundarySourceFor(norm);
|
|
85
|
+
const boundary = boundarySourceFor(norm, platform, reactNativeVersion);
|
|
59
86
|
if (boundary != null) return mod._compile(boundary, filename);
|
|
60
87
|
if (RN_PATH.test(norm)) {
|
|
61
88
|
const src = fs.readFileSync(filename, "utf8");
|
|
62
|
-
if (isFlow(src))
|
|
89
|
+
if (isFlow(src))
|
|
90
|
+
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
63
91
|
} else if (isExtra(norm)) {
|
|
64
92
|
// Configured third-party packages: transform unconditionally — TS `import
|
|
65
93
|
// type`/JSX aren't caught by isFlow, and babel passes plain JS through.
|
|
66
94
|
const src = fs.readFileSync(filename, "utf8");
|
|
67
|
-
return mod._compile(transformRN(filename, src, projectRoot), filename);
|
|
95
|
+
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
68
96
|
}
|
|
69
97
|
return origJs(mod, filename);
|
|
70
98
|
};
|
|
@@ -79,7 +107,7 @@ export function installRequireHooks(projectRoot, transformPkgs = []) {
|
|
|
79
107
|
if (Module._extensions[ext]) continue;
|
|
80
108
|
Module._extensions[ext] = function (mod, filename) {
|
|
81
109
|
const src = fs.readFileSync(filename, "utf8");
|
|
82
|
-
return mod._compile(transformRN(filename, src, projectRoot), filename);
|
|
110
|
+
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
83
111
|
};
|
|
84
112
|
}
|
|
85
113
|
}
|
package/dist/native/loader.mjs
CHANGED
|
@@ -34,12 +34,16 @@ function resolveExtensionless(base) {
|
|
|
34
34
|
// Synthetic URL scheme for preset mocks served to the ESM graph (see below).
|
|
35
35
|
const PRESET_SCHEME = "vitest-native-preset:";
|
|
36
36
|
let PROJECT_ROOT = process.cwd();
|
|
37
|
+
let PLATFORM = "ios";
|
|
38
|
+
let REACT_NATIVE_VERSION = "0.0.0";
|
|
37
39
|
let isExtra = () => false;
|
|
38
40
|
// Preset package name → its mock's named-export list (from the preset definition).
|
|
39
41
|
let presetExports = {};
|
|
40
42
|
|
|
41
43
|
export async function initialize(data) {
|
|
42
44
|
if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
|
|
45
|
+
if (data && data.platform === "android") PLATFORM = "android";
|
|
46
|
+
if (data && data.reactNativeVersion) REACT_NATIVE_VERSION = data.reactNativeVersion;
|
|
43
47
|
if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs);
|
|
44
48
|
if (data && data.presetExports) presetExports = data.presetExports;
|
|
45
49
|
}
|
|
@@ -57,8 +61,13 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
57
61
|
context.parentURL && context.parentURL.startsWith("file:")
|
|
58
62
|
? fileURLToPath(context.parentURL)
|
|
59
63
|
: null;
|
|
60
|
-
if (
|
|
61
|
-
|
|
64
|
+
if (
|
|
65
|
+
parent &&
|
|
66
|
+
(RN_PATH.test(parent) || isExtra(parent)) &&
|
|
67
|
+
specifier.startsWith(".") &&
|
|
68
|
+
!path.extname(specifier)
|
|
69
|
+
) {
|
|
70
|
+
const hit = resolvePlatformFile(path.resolve(path.dirname(parent), specifier), PLATFORM);
|
|
62
71
|
if (hit) return { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
63
72
|
}
|
|
64
73
|
|
|
@@ -100,14 +109,14 @@ export async function load(url, context, nextLoad) {
|
|
|
100
109
|
if (!isRN && !isExtra(norm)) return nextLoad(url, context);
|
|
101
110
|
|
|
102
111
|
if (isRN) {
|
|
103
|
-
const boundary = boundarySourceFor(norm);
|
|
112
|
+
const boundary = boundarySourceFor(norm, PLATFORM, REACT_NATIVE_VERSION);
|
|
104
113
|
if (boundary != null) return { format: "commonjs", source: boundary, shortCircuit: true };
|
|
105
114
|
if (norm.endsWith(".js")) {
|
|
106
115
|
const src = fs.readFileSync(file, "utf8");
|
|
107
116
|
if (isFlow(src))
|
|
108
117
|
return {
|
|
109
118
|
format: "commonjs",
|
|
110
|
-
source: transformRN(file, src, PROJECT_ROOT),
|
|
119
|
+
source: transformRN(file, src, PROJECT_ROOT, PLATFORM),
|
|
111
120
|
shortCircuit: true,
|
|
112
121
|
};
|
|
113
122
|
}
|
|
@@ -117,7 +126,11 @@ export async function load(url, context, nextLoad) {
|
|
|
117
126
|
// Configured third-party package: transform any JS/TS/JSX source to CJS.
|
|
118
127
|
if (TRANSFORMABLE.test(norm)) {
|
|
119
128
|
const src = fs.readFileSync(file, "utf8");
|
|
120
|
-
return {
|
|
129
|
+
return {
|
|
130
|
+
format: "commonjs",
|
|
131
|
+
source: transformRN(file, src, PROJECT_ROOT, PLATFORM),
|
|
132
|
+
shortCircuit: true,
|
|
133
|
+
};
|
|
121
134
|
}
|
|
122
135
|
return nextLoad(url, context);
|
|
123
136
|
}
|