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.
Files changed (54) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +268 -9
  3. package/dist/chunk-CZWwpsFl.cjs +43 -0
  4. package/dist/helpers.cjs +10 -0
  5. package/dist/helpers.d.cts +7 -1
  6. package/dist/helpers.d.mts +7 -1
  7. package/dist/helpers.mjs +10 -1
  8. package/dist/{index-CJqS-y_M.d.cts → index-CJIhukN_.d.mts} +58 -4
  9. package/dist/{index-h4vpIkQO.d.mts → index-DEB7OFaJ.d.cts} +60 -2
  10. package/dist/index.cjs +296 -35
  11. package/dist/index.d.cts +1 -1
  12. package/dist/index.d.mts +1 -1
  13. package/dist/index.mjs +292 -33
  14. package/dist/jest-compat/interop.mjs +30 -0
  15. package/dist/jest-compat/jest-globals.d.mts +3 -0
  16. package/dist/jest-compat/jest-globals.mjs +9 -0
  17. package/dist/jest-compat/noop.d.mts +3 -0
  18. package/dist/jest-compat/noop.mjs +7 -0
  19. package/dist/jest-compat/setup.d.mts +3 -0
  20. package/dist/jest-compat/setup.mjs +41 -0
  21. package/dist/jest-compat.cjs +109 -0
  22. package/dist/jest-compat.d.cts +38 -0
  23. package/dist/jest-compat.d.mts +38 -0
  24. package/dist/jest-compat.mjs +104 -0
  25. package/dist/matchers.cjs +69 -0
  26. package/dist/matchers.d.cts +51 -0
  27. package/dist/matchers.d.mts +51 -0
  28. package/dist/matchers.mjs +66 -0
  29. package/dist/native/boundary.mjs +225 -0
  30. package/dist/native/globals.mjs +112 -0
  31. package/dist/native/hooks.mjs +85 -0
  32. package/dist/native/loader.mjs +123 -0
  33. package/dist/native/match.mjs +9 -0
  34. package/dist/native/reset.mjs +170 -0
  35. package/dist/native/resolve.mjs +22 -0
  36. package/dist/native/runner.mjs +18 -0
  37. package/dist/native/setup.mjs +134 -0
  38. package/dist/native/transform.mjs +79 -0
  39. package/dist/native/worker.mjs +96 -0
  40. package/dist/pool-B4mWN3N5.cjs +60 -0
  41. package/dist/pool-oPTZiSXU.mjs +58 -0
  42. package/dist/{preset-map-Bt4dXkZO.cjs → preset-map-C3jxnkiX.cjs} +6 -1
  43. package/dist/{preset-map-D224CC5w.mjs → preset-map-OJm5IWuL.mjs} +6 -1
  44. package/dist/{presets-9Y4ssfiH.cjs → presets-2I68Ipyl.cjs} +768 -122
  45. package/dist/{presets-CWH0gtM0.mjs → presets-DOGXQzYT.mjs} +732 -87
  46. package/dist/presets.cjs +5 -1
  47. package/dist/presets.d.cts +2 -2
  48. package/dist/presets.d.mts +2 -2
  49. package/dist/presets.mjs +2 -2
  50. package/dist/setup.cjs +903 -121
  51. package/dist/setup.mjs +899 -118
  52. package/docs/migrating-from-jest.md +123 -0
  53. package/docs/migrating-from-vitest-react-native.md +109 -0
  54. package/package.json +67 -8
package/dist/index.mjs CHANGED
@@ -1,9 +1,10 @@
1
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-D224CC5w.mjs";
2
- import { t as presets_exports } from "./presets-CWH0gtM0.mjs";
1
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-OJm5IWuL.mjs";
2
+ import { t as presets_exports } from "./presets-DOGXQzYT.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import path from "node:path";
6
6
  import fs from "node:fs";
7
+ import flowRemoveTypes from "flow-remove-types";
7
8
  //#region src/resolve.ts
8
9
  const PLATFORM_EXTENSIONS_IOS = [
9
10
  ".ios.tsx",
@@ -37,6 +38,158 @@ function getPlatformExtensions(platform) {
37
38
  return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
38
39
  }
39
40
  //#endregion
41
+ //#region src/validate.ts
42
+ const KNOWN_OPTIONS = [
43
+ "platform",
44
+ "presets",
45
+ "mocks",
46
+ "diagnostics",
47
+ "assetExts",
48
+ "engine",
49
+ "transform",
50
+ "hotRuntime"
51
+ ];
52
+ function satisfiesMinimum(version, minimum) {
53
+ const parse = (v) => v.replace(/^[^0-9]*/, "").split(".").map(Number);
54
+ const [aMaj, aMin = 0, aPat = 0] = parse(version);
55
+ const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
56
+ if (aMaj !== bMaj) return aMaj > bMaj;
57
+ if (aMin !== bMin) return aMin > bMin;
58
+ return aPat >= bPat;
59
+ }
60
+ function validatePeerDependency(pkgName, minimumVersion, projectRoot) {
61
+ const req = createRequire(path.join(projectRoot, "package.json"));
62
+ try {
63
+ const { version } = req(req.resolve(`${pkgName}/package.json`));
64
+ if (!satisfiesMinimum(version, minimumVersion)) return `vitest-native requires ${pkgName} >= ${minimumVersion}, but found ${version}. Please upgrade.`;
65
+ return null;
66
+ } catch {
67
+ return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
68
+ }
69
+ }
70
+ function warnUnknownOptions(options) {
71
+ for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
72
+ const suggestion = findClosest(key, KNOWN_OPTIONS);
73
+ const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
74
+ console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
75
+ }
76
+ }
77
+ function findClosest(input, candidates) {
78
+ let best = null;
79
+ let bestDist = Infinity;
80
+ for (const c of candidates) {
81
+ const d = levenshtein(input.toLowerCase(), c.toLowerCase());
82
+ if (d < bestDist && d <= 3) {
83
+ bestDist = d;
84
+ best = c;
85
+ }
86
+ }
87
+ return best;
88
+ }
89
+ function levenshtein(a, b) {
90
+ const m = a.length;
91
+ const n = b.length;
92
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
93
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
94
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
95
+ 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]);
96
+ return dp[m][n];
97
+ }
98
+ //#endregion
99
+ //#region src/native/apply.ts
100
+ /**
101
+ * Vite/Vitest config fragment for the native engine. RN is externalized so it
102
+ * loads through Node's single CJS graph, where the native setup file's hooks
103
+ * Flow-strip it and mock the native boundary.
104
+ */
105
+ /** Escape a package name for use inside a RegExp character-delimited path match. */
106
+ function escapeRe(s) {
107
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
108
+ }
109
+ function nativeEngineConfig(setupFilePath, env, transformPkgs = [], hot) {
110
+ const extraExternal = transformPkgs.map((p) => new RegExp(`[\\\\/]${escapeRe(p)}[\\\\/]`));
111
+ const fullEnv = { ...env };
112
+ if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
113
+ return {
114
+ esbuild: { jsx: "automatic" },
115
+ resolve: {
116
+ 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
+ ],
129
+ dedupe: [
130
+ "react",
131
+ "react-test-renderer",
132
+ "react-is"
133
+ ]
134
+ },
135
+ test: {
136
+ setupFiles: [setupFilePath],
137
+ env: fullEnv,
138
+ ...hot ? {
139
+ pool: hot.pool,
140
+ isolate: false,
141
+ runner: hot.runnerPath
142
+ } : { pool: "threads" },
143
+ server: { deps: { external: [
144
+ /[\\/]react-native[\\/]/,
145
+ /[\\/]@react-native[\\/]/,
146
+ ...extraExternal
147
+ ] } }
148
+ }
149
+ };
150
+ }
151
+ /** Can this project run the native engine? (Both transform deps resolvable.) */
152
+ function isNativeCapable(projectRoot) {
153
+ try {
154
+ const req = createRequire(path.join(projectRoot, "package.json"));
155
+ req.resolve("@react-native/babel-preset");
156
+ req.resolve("@babel/core");
157
+ return true;
158
+ } catch {
159
+ return false;
160
+ }
161
+ }
162
+ /** Resolve the concrete engine for a run. Pure; never throws. */
163
+ function detectEngine(requested, projectRoot, opts) {
164
+ const nativeAvailable = isNativeCapable(projectRoot);
165
+ if (requested === "native") return {
166
+ engine: "native",
167
+ nativeAvailable,
168
+ notice: null
169
+ };
170
+ if (requested === "mock") return {
171
+ engine: "mock",
172
+ nativeAvailable,
173
+ notice: null
174
+ };
175
+ const prefersNative = opts?.autoPrefersNative ?? true;
176
+ if (prefersNative && nativeAvailable) return {
177
+ engine: "native",
178
+ nativeAvailable,
179
+ notice: null
180
+ };
181
+ if (prefersNative) return {
182
+ engine: "mock",
183
+ nativeAvailable: false,
184
+ 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."
185
+ };
186
+ return {
187
+ engine: "mock",
188
+ nativeAvailable,
189
+ notice: null
190
+ };
191
+ }
192
+ //#endregion
40
193
  //#region src/plugin.ts
41
194
  const DEFAULT_ASSET_EXTS = [
42
195
  "png",
@@ -65,40 +218,55 @@ const DEFAULT_ASSET_EXTS = [
65
218
  function stripFsPrefix(id) {
66
219
  return id.startsWith("/@fs/") ? id.slice(4) : id;
67
220
  }
68
- /**
69
- * Check if a package is installed from the consumer's project root,
70
- * not from the plugin's own node_modules. This is critical for monorepos
71
- * and non-hoisted layouts (pnpm strict, yarn PnP).
72
- */
73
- function isPackageInstalled(packageName, projectRoot) {
74
- try {
75
- createRequire(path.join(projectRoot, "package.json")).resolve(packageName);
76
- return true;
77
- } catch {
78
- return false;
79
- }
80
- }
81
221
  async function autoDetectPresets(diagnostics, projectRoot) {
82
222
  const detected = [];
83
223
  const presetFactories = await import("./presets.mjs");
84
- for (const [pkgName, exportName] of Object.entries(AUTO_DETECT_PRESETS)) if (isPackageInstalled(pkgName, projectRoot)) {
85
- const factory = presetFactories[exportName];
86
- if (typeof factory === "function") {
87
- detected.push(factory());
88
- if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
89
- }
224
+ const req = createRequire(path.join(projectRoot, "package.json"));
225
+ for (const [pkgName, exportName] of Object.entries(AUTO_DETECT_PRESETS)) {
226
+ let installed = false;
227
+ try {
228
+ req.resolve(pkgName);
229
+ installed = true;
230
+ } catch {}
231
+ if (installed) {
232
+ const factory = presetFactories[exportName];
233
+ if (typeof factory === "function") {
234
+ detected.push(factory());
235
+ if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
236
+ }
237
+ } else if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
90
238
  }
91
239
  return detected;
92
240
  }
241
+ /**
242
+ * Synchronously resolve the export-names of presets whose package is installed.
243
+ * Used by the native-engine config path (which can't await the factory imports)
244
+ * to tell the native setup file which preset mocks to build. Returns deduped
245
+ * preset names (e.g. ["reanimated", "navigation"]).
246
+ */
247
+ function autoDetectPresetNames(projectRoot, diagnostics) {
248
+ const req = createRequire(path.join(projectRoot, "package.json"));
249
+ const names = /* @__PURE__ */ new Set();
250
+ for (const [pkgName, exportName] of Object.entries(AUTO_DETECT_PRESETS)) try {
251
+ req.resolve(pkgName);
252
+ names.add(exportName);
253
+ if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
254
+ } catch {
255
+ if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
256
+ }
257
+ return [...names];
258
+ }
93
259
  async function resolveOptions(options = {}, projectRoot) {
94
260
  const platform = options.platform ?? "ios";
95
261
  const diagnostics = options.diagnostics ?? false;
262
+ const engine = options.engine === "native" ? "native" : "mock";
96
263
  const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
97
264
  let presets;
98
265
  if (options.presets) presets = options.presets;
99
266
  else presets = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
100
267
  return {
101
268
  platform,
269
+ engine,
102
270
  diagnostics,
103
271
  extensions: getPlatformExtensions(platform),
104
272
  presets,
@@ -212,35 +380,69 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
212
380
  */
213
381
  function reactNative(options) {
214
382
  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);
215
384
  let resolved;
216
385
  const presetModules = /* @__PURE__ */ new Map();
217
386
  const presetExportNames = /* @__PURE__ */ new Map();
218
387
  let assetPattern;
388
+ const resolveCache = /* @__PURE__ */ new Map();
389
+ const virtualCodeCache = /* @__PURE__ */ new Map();
219
390
  const thisDir = path.dirname(fileURLToPath(import.meta.url));
220
391
  let setupFilePath = path.resolve(thisDir, "setup.mjs");
221
392
  if (!fs.existsSync(setupFilePath)) {
222
393
  const srcPath = path.resolve(thisDir, "setup.ts");
223
394
  if (fs.existsSync(srcPath)) setupFilePath = srcPath;
224
395
  }
396
+ const nativeSetupPath = path.resolve(thisDir, "native/setup.mjs");
397
+ const nativeWorkerPath = path.resolve(thisDir, "native/worker.mjs");
398
+ const nativeRunnerPath = path.resolve(thisDir, "native/runner.mjs");
225
399
  const platform = options?.platform ?? "ios";
226
400
  const diagnostics = options?.diagnostics ?? false;
401
+ const requestedEngine = options?.engine ?? "auto";
402
+ const transformPkgs = (options?.transform ?? []).filter((p) => typeof p === "string" && p.length > 0);
403
+ const hotRuntimeOpt = options?.hotRuntime ?? false;
404
+ const hotRuntime = hotRuntimeOpt !== false;
405
+ const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
406
+ let engine = requestedEngine === "native" ? "native" : "mock";
227
407
  const extensions = getPlatformExtensions(platform);
228
408
  return {
229
409
  name: "vitest-native",
230
410
  enforce: "pre",
231
- config(userConfig, _env) {
411
+ async config(userConfig, _env) {
232
412
  const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
413
+ const decision = detectEngine(requestedEngine, resolvedRoot);
414
+ engine = decision.engine;
415
+ if (decision.notice) console.log(decision.notice);
233
416
  const env = {
234
417
  VITEST_NATIVE_PLATFORM: platform,
235
418
  VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
236
419
  VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
237
420
  };
421
+ if (engine === "native") {
422
+ const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
423
+ if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
424
+ return nativeEngineConfig(nativeSetupPath, env, transformPkgs, hotRuntime ? {
425
+ pool: (await import("./pool-oPTZiSXU.mjs")).nativePool({
426
+ workerEntry: nativeWorkerPath,
427
+ recycleAfterFiles: hotRecycle.recycleAfterFiles,
428
+ memoryLimit: hotRecycle.memoryLimit
429
+ }),
430
+ runnerPath: nativeRunnerPath
431
+ } : void 0);
432
+ }
433
+ if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
238
434
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
239
435
  if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
240
436
  return {
437
+ esbuild: { jsx: "automatic" },
241
438
  resolve: {
242
439
  extensions,
243
- conditions: ["react-native"]
440
+ conditions: ["react-native"],
441
+ dedupe: [
442
+ "react",
443
+ "react-test-renderer",
444
+ "react-is"
445
+ ]
244
446
  },
245
447
  test: {
246
448
  setupFiles: [setupFilePath],
@@ -249,7 +451,27 @@ function reactNative(options) {
249
451
  };
250
452
  },
251
453
  async configResolved(config) {
454
+ for (const { name, range } of [
455
+ {
456
+ name: "vitest",
457
+ range: "4.0.0"
458
+ },
459
+ {
460
+ name: "vite",
461
+ range: "5.0.0"
462
+ },
463
+ {
464
+ name: "react",
465
+ range: "18.0.0"
466
+ }
467
+ ]) {
468
+ const error = validatePeerDependency(name, range, config.root);
469
+ if (error) console.error(`[vitest-native] ${error}`);
470
+ }
471
+ const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root);
472
+ if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
252
473
  resolved = await resolveOptions(options, config.root);
474
+ resolved.engine = engine;
253
475
  for (const preset of resolved.presets) for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
254
476
  presetModules.set(moduleName, presetModule.factory);
255
477
  presetExportNames.set(moduleName, presetModule.exports);
@@ -257,40 +479,77 @@ function reactNative(options) {
257
479
  assetPattern = new RegExp(`\\.(${resolved.assetExts.join("|")})$`);
258
480
  },
259
481
  resolveId(source, importer) {
482
+ if (engine === "native") {
483
+ if (presetModules.has(source)) return `\0virtual:preset:${source}`;
484
+ return;
485
+ }
260
486
  if (source === "react-native") return "\0virtual:react-native";
261
487
  if (source.startsWith("react-native/")) return `\0virtual:rn-subpath:${source}`;
262
488
  if (presetModules.has(source)) return `\0virtual:preset:${source}`;
263
489
  if (importer && importer.includes("node_modules") && source.startsWith(".") && !path.extname(source)) {
490
+ const cacheKey = `${importer}\0${source}`;
491
+ const cached = resolveCache.get(cacheKey);
492
+ if (cached !== void 0) return cached;
264
493
  const importerDir = path.dirname(importer);
265
494
  const absolute = path.resolve(importerDir, source);
266
495
  for (const ext of extensions) {
267
496
  const candidate = absolute + ext;
268
- if (fs.existsSync(candidate)) return candidate;
497
+ if (fs.existsSync(candidate)) {
498
+ resolveCache.set(cacheKey, candidate);
499
+ return candidate;
500
+ }
269
501
  }
270
502
  for (const ext of extensions) {
271
503
  const candidate = path.join(absolute, `index${ext}`);
272
- if (fs.existsSync(candidate)) return candidate;
504
+ if (fs.existsSync(candidate)) {
505
+ resolveCache.set(cacheKey, candidate);
506
+ return candidate;
507
+ }
273
508
  }
509
+ resolveCache.set(cacheKey, void 0);
274
510
  }
275
511
  },
276
512
  load(id) {
277
- if (id === "\0virtual:react-native") return "export default {};";
278
- if (id.startsWith("\0virtual:rn-subpath:")) return [
279
- `const _rn = globalThis.__vitest_native_mock || {};`,
280
- ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
281
- `export default _rn;`
282
- ].join("\n");
283
513
  if (id.startsWith("\0virtual:preset:")) {
514
+ const cached = virtualCodeCache.get(id);
515
+ if (cached) return cached;
284
516
  const moduleName = id.slice(16);
285
517
  const exportNames = presetExportNames.get(moduleName) || [];
286
- return [
518
+ const code = [
287
519
  `const _m = (globalThis.__vitest_native_preset_mocks || {})['${moduleName}'] || {};`,
288
520
  ...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
289
- `export default _m;`
521
+ `export default ('default' in _m ? _m['default'] : _m);`
290
522
  ].join("\n");
523
+ virtualCodeCache.set(id, code);
524
+ return code;
525
+ }
526
+ if (engine === "native") return void 0;
527
+ if (id === "\0virtual:react-native") return "export default {};";
528
+ if (id.startsWith("\0virtual:rn-subpath:")) {
529
+ let code = virtualCodeCache.get("\0rn-subpath");
530
+ if (!code) {
531
+ code = [
532
+ `const _rn = globalThis.__vitest_native_mock || {};`,
533
+ ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
534
+ `export default _rn;`
535
+ ].join("\n");
536
+ virtualCodeCache.set("\0rn-subpath", code);
537
+ }
538
+ return code;
291
539
  }
292
540
  const fsPath = stripFsPrefix(id);
293
541
  if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
542
+ },
543
+ transform(code, id) {
544
+ if (engine === "native") return void 0;
545
+ if (!id.includes("node_modules")) return void 0;
546
+ if (!id.includes("react-native") || !id.endsWith(".js")) return void 0;
547
+ if (!code.includes("@flow")) return void 0;
548
+ const stripped = flowRemoveTypes(code, { all: true });
549
+ return {
550
+ code: stripped.toString(),
551
+ map: stripped.generateMap()
552
+ };
294
553
  }
295
554
  };
296
555
  }
@@ -0,0 +1,30 @@
1
+ // Jest-style CommonJS interop for jest.mock factory return values.
2
+ //
3
+ // Jest treats a `jest.mock('m', factory)` factory's return as CommonJS
4
+ // `module.exports`, then resolves a default import via `_interopRequireDefault`:
5
+ // import X from 'm' → exports.__esModule ? exports.default : exports
6
+ // import { a } from 'm' → exports.a
7
+ //
8
+ // Vitest instead treats the factory return as an ES-module namespace, so a
9
+ // default import only sees a literal `default` key. That breaks the two most
10
+ // common Jest manual-mock shapes:
11
+ // jest.mock('m', () => Component) // a function/component, no object
12
+ // jest.mock('m', () => ({ a, b })) // named-only, consumed as `import X from`
13
+ //
14
+ // jestMockTransform wraps each jest.mock/doMock factory so its return passes
15
+ // through this — reproducing Jest's interop while leaving genuinely ES-shaped
16
+ // returns (those with `__esModule` or an explicit `default`) untouched.
17
+ export function jestMockInterop(mod) {
18
+ if (mod == null) return mod;
19
+ const t = typeof mod;
20
+ if (t === "object" || t === "function") {
21
+ // Already ES-shaped — respect the author's/real module's default export.
22
+ if (mod.__esModule || "default" in mod) return mod;
23
+ // CJS exports: a default import receives the whole module (object or
24
+ // function); named imports keep working off its keys (object props / fn
25
+ // statics). `{ ...mod }` copies own enumerable props for the named side.
26
+ return { ...mod, default: mod };
27
+ }
28
+ // Primitive export (rare): expose as default.
29
+ return { default: mod };
30
+ }
@@ -0,0 +1,3 @@
1
+ // `@jest/globals` shim — re-exports Vitest globals and maps `jest` -> `vi`.
2
+ export { expect, describe, it, test, beforeAll, afterAll, beforeEach, afterEach } from "vitest";
3
+ export declare const jest: typeof import("vitest").vi;
@@ -0,0 +1,9 @@
1
+ // vitest-native/jest-compat/extend-expect-noop → @jest/globals shim
2
+ //
3
+ // Alias `@jest/globals` to this so libraries that import it (notably
4
+ // @testing-library/react-native < 12) load under Vitest. Re-exports the Vitest
5
+ // globals under the names Jest's module provides, and maps `jest` → `vi`.
6
+ import { expect, describe, it, test, beforeAll, afterAll, beforeEach, afterEach, vi } from "vitest";
7
+
8
+ export { expect, describe, it, test, beforeAll, afterAll, beforeEach, afterEach };
9
+ export const jest = vi;
@@ -0,0 +1,3 @@
1
+ // No-op for `@testing-library/jest-native/extend-expect` (matchers already registered).
2
+ declare const _default: Record<string, never>;
3
+ export default _default;
@@ -0,0 +1,7 @@
1
+ // vitest-native/jest-compat/extend-expect-noop
2
+ //
3
+ // Alias `@testing-library/jest-native/extend-expect` to this. jest-native's
4
+ // matchers are already registered by vitest-native's setup (it extends expect
5
+ // with the RNTL built-in matchers), so importing the jest-native extend-expect
6
+ // entry just needs to be a harmless no-op rather than pulling in jest internals.
7
+ export default {};
@@ -0,0 +1,3 @@
1
+ // Side-effect-only module: installs a `jest` global backed by Vitest's `vi`.
2
+ // (Type-only marker so this is a module without an empty `export {}` specifier.)
3
+ export type VitestNativeJestCompatSetup = void;
@@ -0,0 +1,41 @@
1
+ // vitest-native/jest-compat/setup
2
+ //
3
+ // Add to `test.setupFiles` to give an existing Jest suite a `jest` global backed
4
+ // by Vitest's `vi`. Real RN suites lean on `jest.fn`/`jest.requireActual`/
5
+ // `jest.useFakeTimers` etc.; Vitest exposes the same API as `vi` minus the sync
6
+ // `requireActual`/`requireMock`, which we add here.
7
+ //
8
+ // Top-level `jest.mock(...)` hoisting: Vitest only hoists calls on the `vi`/
9
+ // `vitest` identifier, so a raw `jest.mock('react-native', factory)` would run
10
+ // AFTER imports and not apply. Add the `jestMockTransform()` plugin (exported from
11
+ // this entry) to rewrite top-level jest.mock/unmock/doMock to the hoisted vi.*
12
+ // form at transform time. `jest.fn`, `jest.spyOn`, `jest.requireActual`,
13
+ // `jest.useFakeTimers` work at runtime via the `jest` global installed here.
14
+ import { vi } from "vitest";
15
+ import { createRequire } from "node:module";
16
+ import path from "node:path";
17
+ import { jestMockInterop } from "./interop.mjs";
18
+
19
+ // Resolve modules from the consumer project root, not this file's location, so
20
+ // `jest.requireActual('some-project-dep')` resolves the same module the suite sees.
21
+ const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
22
+ const require = createRequire(path.join(projectRoot, "package.json"));
23
+
24
+ if (typeof vi.requireActual !== "function") vi.requireActual = (m) => require(m);
25
+ if (typeof vi.requireMock !== "function") vi.requireMock = (m) => require(m);
26
+ // `jest.setTimeout(ms)` has no global `vi` equivalent — no-op so suites that call
27
+ // it at top level don't crash.
28
+ if (typeof vi.setTimeout !== "function") vi.setTimeout = () => {};
29
+
30
+ globalThis.jest = vi;
31
+
32
+ // jest.mock factories are wrapped by jestMockTransform to route their return
33
+ // value through Jest's CommonJS interop (so `import X from` sees the whole mock,
34
+ // and `() => Component` factories work). The wrapper calls this global.
35
+ if (typeof globalThis.__vnInteropMock !== "function") globalThis.__vnInteropMock = jestMockInterop;
36
+
37
+ // Jest test modules (and `jest.mock` factories) routinely call `require(...)`
38
+ // synchronously — e.g. `jest.mock('x', () => require('react-native').View)`. ESM
39
+ // test modules have no `require` binding, so provide a global one resolved from the
40
+ // project root. Guarded so it never clobbers an existing CJS `require`.
41
+ if (typeof globalThis.require !== "function") globalThis.require = require;
@@ -0,0 +1,109 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_chunk = require("./chunk-CZWwpsFl.cjs");
3
+ let magic_string = require("magic-string");
4
+ magic_string = require_chunk.__toESM(magic_string);
5
+ //#region src/jest-compat/transform.ts
6
+ const HOISTABLE = new Set([
7
+ "mock",
8
+ "unmock",
9
+ "doMock",
10
+ "doUnmock"
11
+ ]);
12
+ const WITH_FACTORY = new Set(["mock", "doMock"]);
13
+ const TRANSFORMABLE = /\.(?:[cm]?[jt]sx?)$/;
14
+ const HAS_JEST_MOCK = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
15
+ /** Visit every node in an ESTree AST (depth-first), calling `fn` on each. */
16
+ function walk(node, fn) {
17
+ if (!node || typeof node.type !== "string") return;
18
+ fn(node);
19
+ for (const key in node) {
20
+ if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
21
+ const child = node[key];
22
+ if (Array.isArray(child)) {
23
+ for (const c of child) if (c && typeof c.type === "string") walk(c, fn);
24
+ } else if (child && typeof child.type === "string") walk(child, fn);
25
+ }
26
+ }
27
+ /**
28
+ * Vite plugin that adapts a Jest suite's `jest.mock(...)` calls for Vitest:
29
+ *
30
+ * 1. **Hoisting** — rewrites the `jest` object of `jest.mock`/`unmock`/`doMock`/
31
+ * `doUnmock` to `vi`, so Vitest's hoister (which only recognises `vi`/`vitest`)
32
+ * lifts them above the imports. Without this a top-level `jest.mock(...)` runs
33
+ * after imports and silently doesn't apply.
34
+ *
35
+ * 2. **CJS interop** — wraps each `jest.mock`/`doMock` factory so its return value
36
+ * passes through Jest's `_interopRequireDefault` semantics (see interop.mjs).
37
+ * Jest treats the factory return as `module.exports`; Vitest treats it as an ES
38
+ * namespace. This bridges the two common Jest shapes that otherwise break:
39
+ * jest.mock('m', () => Component) // Vitest: "not returning an object"
40
+ * jest.mock('m', () => ({ a, b })) // Vitest: default import is undefined
41
+ * A factory already returning an ES shape (`__esModule`/explicit `default`) is
42
+ * passed through unchanged.
43
+ *
44
+ * Opt-in: add after `reactNative()`; pair with `jestCompatSetup` + `globals: true`.
45
+ */
46
+ function jestMockTransform() {
47
+ return {
48
+ name: "vitest-native:jest-mock-hoist",
49
+ transform(code, id) {
50
+ if (id.includes("/node_modules/")) return null;
51
+ const file = id.split("?")[0];
52
+ if (!TRANSFORMABLE.test(file)) return null;
53
+ if (!HAS_JEST_MOCK.test(code)) return null;
54
+ let ast;
55
+ try {
56
+ ast = this.parse(code);
57
+ } catch {
58
+ return null;
59
+ }
60
+ const s = new magic_string.default(code);
61
+ let changed = false;
62
+ walk(ast, (node) => {
63
+ if (node.type !== "CallExpression") return;
64
+ const callee = node.callee;
65
+ if (!callee || callee.type !== "MemberExpression" || callee.computed) return;
66
+ const obj = callee.object;
67
+ const prop = callee.property;
68
+ if (!obj || obj.type !== "Identifier" || obj.name !== "jest") return;
69
+ if (!prop || prop.type !== "Identifier" || !HOISTABLE.has(prop.name)) return;
70
+ s.overwrite(obj.start, obj.end, "vi");
71
+ changed = true;
72
+ if (WITH_FACTORY.has(prop.name) && node.arguments.length >= 2) {
73
+ const factory = node.arguments[1];
74
+ if (factory.type === "ArrowFunctionExpression" || factory.type === "FunctionExpression") {
75
+ s.appendLeft(factory.start, "() => globalThis.__vnInteropMock((");
76
+ s.appendRight(factory.end, ")())");
77
+ }
78
+ }
79
+ });
80
+ if (!changed) return null;
81
+ return {
82
+ code: s.toString(),
83
+ map: s.generateMap({ hires: true })
84
+ };
85
+ }
86
+ };
87
+ }
88
+ //#endregion
89
+ //#region src/jest-compat/index.ts
90
+ /** Setup-file specifier: gives the suite a `jest` global backed by Vitest's `vi`. */
91
+ const jestCompatSetup = "vitest-native/jest-compat/setup";
92
+ /**
93
+ * `resolve.alias` entries that redirect Jest-only modules to Vitest-backed shims:
94
+ * - `@jest/globals` → a shim re-exporting Vitest globals (unblocks RNTL < 12)
95
+ * - `@testing-library/jest-native/extend-expect` → a no-op (matchers are already
96
+ * registered by vitest-native's setup)
97
+ *
98
+ * Spread into your config's `resolve.alias`.
99
+ */
100
+ function jestCompatAliases() {
101
+ return {
102
+ "@jest/globals": "vitest-native/jest-compat/jest-globals",
103
+ "@testing-library/jest-native/extend-expect": "vitest-native/jest-compat/extend-expect-noop"
104
+ };
105
+ }
106
+ //#endregion
107
+ exports.jestCompatAliases = jestCompatAliases;
108
+ exports.jestCompatSetup = jestCompatSetup;
109
+ exports.jestMockTransform = jestMockTransform;