vitest-native 0.3.0 → 0.4.1

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 (50) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.md +254 -11
  3. package/dist/chunk-CZWwpsFl.cjs +43 -0
  4. package/dist/{index-CJqS-y_M.d.cts → index-CJIhukN_.d.mts} +58 -4
  5. package/dist/{index-h4vpIkQO.d.mts → index-DEB7OFaJ.d.cts} +60 -2
  6. package/dist/index.cjs +252 -21
  7. package/dist/index.d.cts +1 -1
  8. package/dist/index.d.mts +1 -1
  9. package/dist/index.mjs +248 -18
  10. package/dist/jest-compat/interop.mjs +30 -0
  11. package/dist/jest-compat/jest-globals.d.mts +3 -0
  12. package/dist/jest-compat/jest-globals.mjs +9 -0
  13. package/dist/jest-compat/noop.d.mts +3 -0
  14. package/dist/jest-compat/noop.mjs +7 -0
  15. package/dist/jest-compat/setup.d.mts +3 -0
  16. package/dist/jest-compat/setup.mjs +41 -0
  17. package/dist/jest-compat.cjs +109 -0
  18. package/dist/jest-compat.d.cts +38 -0
  19. package/dist/jest-compat.d.mts +38 -0
  20. package/dist/jest-compat.mjs +104 -0
  21. package/dist/matchers.cjs +69 -0
  22. package/dist/matchers.d.cts +51 -0
  23. package/dist/matchers.d.mts +51 -0
  24. package/dist/matchers.mjs +66 -0
  25. package/dist/native/boundary.mjs +225 -0
  26. package/dist/native/globals.mjs +112 -0
  27. package/dist/native/hooks.mjs +85 -0
  28. package/dist/native/loader.mjs +123 -0
  29. package/dist/native/match.mjs +9 -0
  30. package/dist/native/reset.mjs +170 -0
  31. package/dist/native/resolve.mjs +22 -0
  32. package/dist/native/runner.mjs +18 -0
  33. package/dist/native/setup.mjs +134 -0
  34. package/dist/native/transform.mjs +79 -0
  35. package/dist/native/worker.mjs +96 -0
  36. package/dist/pool-B4mWN3N5.cjs +60 -0
  37. package/dist/pool-oPTZiSXU.mjs +58 -0
  38. package/dist/{preset-map-DxU6UgYS.cjs → preset-map-C3jxnkiX.cjs} +5 -1
  39. package/dist/{preset-map-BTpoNH3G.mjs → preset-map-OJm5IWuL.mjs} +5 -1
  40. package/dist/{presets-B-spxZz7.cjs → presets-2I68Ipyl.cjs} +437 -41
  41. package/dist/{presets-DvrcfEPz.mjs → presets-DOGXQzYT.mjs} +401 -6
  42. package/dist/presets.cjs +5 -1
  43. package/dist/presets.d.cts +2 -2
  44. package/dist/presets.d.mts +2 -2
  45. package/dist/presets.mjs +2 -2
  46. package/dist/setup.cjs +263 -115
  47. package/dist/setup.mjs +259 -112
  48. package/docs/migrating-from-jest.md +123 -0
  49. package/docs/migrating-from-vitest-react-native.md +109 -0
  50. package/package.json +65 -9
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-BTpoNH3G.mjs";
2
- import { t as presets_exports } from "./presets-DvrcfEPz.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";
@@ -38,6 +38,158 @@ function getPlatformExtensions(platform) {
38
38
  return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
39
39
  }
40
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
41
193
  //#region src/plugin.ts
42
194
  const DEFAULT_ASSET_EXTS = [
43
195
  "png",
@@ -82,19 +234,39 @@ async function autoDetectPresets(diagnostics, projectRoot) {
82
234
  detected.push(factory());
83
235
  if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
84
236
  }
85
- }
237
+ } else if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
86
238
  }
87
239
  return detected;
88
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
+ }
89
259
  async function resolveOptions(options = {}, projectRoot) {
90
260
  const platform = options.platform ?? "ios";
91
261
  const diagnostics = options.diagnostics ?? false;
262
+ const engine = options.engine === "native" ? "native" : "mock";
92
263
  const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
93
264
  let presets;
94
265
  if (options.presets) presets = options.presets;
95
266
  else presets = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
96
267
  return {
97
268
  platform,
269
+ engine,
98
270
  diagnostics,
99
271
  extensions: getPlatformExtensions(platform),
100
272
  presets,
@@ -208,6 +380,7 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
208
380
  */
209
381
  function reactNative(options) {
210
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);
211
384
  let resolved;
212
385
  const presetModules = /* @__PURE__ */ new Map();
213
386
  const presetExportNames = /* @__PURE__ */ new Map();
@@ -220,25 +393,56 @@ function reactNative(options) {
220
393
  const srcPath = path.resolve(thisDir, "setup.ts");
221
394
  if (fs.existsSync(srcPath)) setupFilePath = srcPath;
222
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");
223
399
  const platform = options?.platform ?? "ios";
224
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";
225
407
  const extensions = getPlatformExtensions(platform);
226
408
  return {
227
409
  name: "vitest-native",
228
410
  enforce: "pre",
229
- config(userConfig, _env) {
411
+ async config(userConfig, _env) {
230
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);
231
416
  const env = {
232
417
  VITEST_NATIVE_PLATFORM: platform,
233
418
  VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
234
419
  VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
235
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.`);
236
434
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
237
435
  if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
238
436
  return {
437
+ esbuild: { jsx: "automatic" },
239
438
  resolve: {
240
439
  extensions,
241
- conditions: ["react-native"]
440
+ conditions: ["react-native"],
441
+ dedupe: [
442
+ "react",
443
+ "react-test-renderer",
444
+ "react-is"
445
+ ]
242
446
  },
243
447
  test: {
244
448
  setupFiles: [setupFilePath],
@@ -247,7 +451,27 @@ function reactNative(options) {
247
451
  };
248
452
  },
249
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}`);
250
473
  resolved = await resolveOptions(options, config.root);
474
+ resolved.engine = engine;
251
475
  for (const preset of resolved.presets) for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
252
476
  presetModules.set(moduleName, presetModule.factory);
253
477
  presetExportNames.set(moduleName, presetModule.exports);
@@ -255,6 +479,10 @@ function reactNative(options) {
255
479
  assetPattern = new RegExp(`\\.(${resolved.assetExts.join("|")})$`);
256
480
  },
257
481
  resolveId(source, importer) {
482
+ if (engine === "native") {
483
+ if (presetModules.has(source)) return `\0virtual:preset:${source}`;
484
+ return;
485
+ }
258
486
  if (source === "react-native") return "\0virtual:react-native";
259
487
  if (source.startsWith("react-native/")) return `\0virtual:rn-subpath:${source}`;
260
488
  if (presetModules.has(source)) return `\0virtual:preset:${source}`;
@@ -282,6 +510,20 @@ function reactNative(options) {
282
510
  }
283
511
  },
284
512
  load(id) {
513
+ if (id.startsWith("\0virtual:preset:")) {
514
+ const cached = virtualCodeCache.get(id);
515
+ if (cached) return cached;
516
+ const moduleName = id.slice(16);
517
+ const exportNames = presetExportNames.get(moduleName) || [];
518
+ const code = [
519
+ `const _m = (globalThis.__vitest_native_preset_mocks || {})['${moduleName}'] || {};`,
520
+ ...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
521
+ `export default ('default' in _m ? _m['default'] : _m);`
522
+ ].join("\n");
523
+ virtualCodeCache.set(id, code);
524
+ return code;
525
+ }
526
+ if (engine === "native") return void 0;
285
527
  if (id === "\0virtual:react-native") return "export default {};";
286
528
  if (id.startsWith("\0virtual:rn-subpath:")) {
287
529
  let code = virtualCodeCache.get("\0rn-subpath");
@@ -295,23 +537,11 @@ function reactNative(options) {
295
537
  }
296
538
  return code;
297
539
  }
298
- if (id.startsWith("\0virtual:preset:")) {
299
- const cached = virtualCodeCache.get(id);
300
- if (cached) return cached;
301
- const moduleName = id.slice(16);
302
- const exportNames = presetExportNames.get(moduleName) || [];
303
- const code = [
304
- `const _m = (globalThis.__vitest_native_preset_mocks || {})['${moduleName}'] || {};`,
305
- ...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
306
- `export default _m;`
307
- ].join("\n");
308
- virtualCodeCache.set(id, code);
309
- return code;
310
- }
311
540
  const fsPath = stripFsPrefix(id);
312
541
  if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
313
542
  },
314
543
  transform(code, id) {
544
+ if (engine === "native") return void 0;
315
545
  if (!id.includes("node_modules")) return void 0;
316
546
  if (!id.includes("react-native") || !id.endsWith(".js")) return void 0;
317
547
  if (!code.includes("@flow")) return void 0;
@@ -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;
@@ -0,0 +1,38 @@
1
+ import { Plugin } from "vite";
2
+
3
+ //#region src/jest-compat/transform.d.ts
4
+ /**
5
+ * Vite plugin that adapts a Jest suite's `jest.mock(...)` calls for Vitest:
6
+ *
7
+ * 1. **Hoisting** — rewrites the `jest` object of `jest.mock`/`unmock`/`doMock`/
8
+ * `doUnmock` to `vi`, so Vitest's hoister (which only recognises `vi`/`vitest`)
9
+ * lifts them above the imports. Without this a top-level `jest.mock(...)` runs
10
+ * after imports and silently doesn't apply.
11
+ *
12
+ * 2. **CJS interop** — wraps each `jest.mock`/`doMock` factory so its return value
13
+ * passes through Jest's `_interopRequireDefault` semantics (see interop.mjs).
14
+ * Jest treats the factory return as `module.exports`; Vitest treats it as an ES
15
+ * namespace. This bridges the two common Jest shapes that otherwise break:
16
+ * jest.mock('m', () => Component) // Vitest: "not returning an object"
17
+ * jest.mock('m', () => ({ a, b })) // Vitest: default import is undefined
18
+ * A factory already returning an ES shape (`__esModule`/explicit `default`) is
19
+ * passed through unchanged.
20
+ *
21
+ * Opt-in: add after `reactNative()`; pair with `jestCompatSetup` + `globals: true`.
22
+ */
23
+ declare function jestMockTransform(): Plugin;
24
+ //#endregion
25
+ //#region src/jest-compat/index.d.ts
26
+ /** Setup-file specifier: gives the suite a `jest` global backed by Vitest's `vi`. */
27
+ declare const jestCompatSetup = "vitest-native/jest-compat/setup";
28
+ /**
29
+ * `resolve.alias` entries that redirect Jest-only modules to Vitest-backed shims:
30
+ * - `@jest/globals` → a shim re-exporting Vitest globals (unblocks RNTL < 12)
31
+ * - `@testing-library/jest-native/extend-expect` → a no-op (matchers are already
32
+ * registered by vitest-native's setup)
33
+ *
34
+ * Spread into your config's `resolve.alias`.
35
+ */
36
+ declare function jestCompatAliases(): Record<string, string>;
37
+ //#endregion
38
+ export { jestCompatAliases, jestCompatSetup, jestMockTransform };
@@ -0,0 +1,38 @@
1
+ import { Plugin } from "vite";
2
+
3
+ //#region src/jest-compat/transform.d.ts
4
+ /**
5
+ * Vite plugin that adapts a Jest suite's `jest.mock(...)` calls for Vitest:
6
+ *
7
+ * 1. **Hoisting** — rewrites the `jest` object of `jest.mock`/`unmock`/`doMock`/
8
+ * `doUnmock` to `vi`, so Vitest's hoister (which only recognises `vi`/`vitest`)
9
+ * lifts them above the imports. Without this a top-level `jest.mock(...)` runs
10
+ * after imports and silently doesn't apply.
11
+ *
12
+ * 2. **CJS interop** — wraps each `jest.mock`/`doMock` factory so its return value
13
+ * passes through Jest's `_interopRequireDefault` semantics (see interop.mjs).
14
+ * Jest treats the factory return as `module.exports`; Vitest treats it as an ES
15
+ * namespace. This bridges the two common Jest shapes that otherwise break:
16
+ * jest.mock('m', () => Component) // Vitest: "not returning an object"
17
+ * jest.mock('m', () => ({ a, b })) // Vitest: default import is undefined
18
+ * A factory already returning an ES shape (`__esModule`/explicit `default`) is
19
+ * passed through unchanged.
20
+ *
21
+ * Opt-in: add after `reactNative()`; pair with `jestCompatSetup` + `globals: true`.
22
+ */
23
+ declare function jestMockTransform(): Plugin;
24
+ //#endregion
25
+ //#region src/jest-compat/index.d.ts
26
+ /** Setup-file specifier: gives the suite a `jest` global backed by Vitest's `vi`. */
27
+ declare const jestCompatSetup = "vitest-native/jest-compat/setup";
28
+ /**
29
+ * `resolve.alias` entries that redirect Jest-only modules to Vitest-backed shims:
30
+ * - `@jest/globals` → a shim re-exporting Vitest globals (unblocks RNTL < 12)
31
+ * - `@testing-library/jest-native/extend-expect` → a no-op (matchers are already
32
+ * registered by vitest-native's setup)
33
+ *
34
+ * Spread into your config's `resolve.alias`.
35
+ */
36
+ declare function jestCompatAliases(): Record<string, string>;
37
+ //#endregion
38
+ export { jestCompatAliases, jestCompatSetup, jestMockTransform };