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.
Files changed (37) hide show
  1. package/CHANGELOG.md +98 -1
  2. package/README.md +270 -180
  3. package/dist/helpers.cjs +13 -0
  4. package/dist/helpers.mjs +13 -0
  5. package/dist/{index-DEB7OFaJ.d.cts → index-DGNLmGjq.d.mts} +19 -12
  6. package/dist/{index-CJIhukN_.d.mts → index-Dr3WvKWI.d.cts} +21 -10
  7. package/dist/index.cjs +106 -39
  8. package/dist/index.d.cts +1 -1
  9. package/dist/index.d.mts +1 -1
  10. package/dist/index.mjs +103 -36
  11. package/dist/jest-compat.cjs +1 -1
  12. package/dist/native/boundary.mjs +82 -32
  13. package/dist/native/globals.mjs +1 -0
  14. package/dist/native/hooks.mjs +35 -7
  15. package/dist/native/loader.mjs +18 -5
  16. package/dist/native/reset.mjs +79 -43
  17. package/dist/native/resolve.mjs +25 -7
  18. package/dist/native/runner.mjs +13 -2
  19. package/dist/native/setup.mjs +95 -4
  20. package/dist/native/transform.mjs +15 -9
  21. package/dist/native/worker.mjs +20 -3
  22. package/dist/{pool-oPTZiSXU.mjs → pool-B7LBfcMQ.mjs} +10 -1
  23. package/dist/{pool-B4mWN3N5.cjs → pool-p54QV1dQ.cjs} +11 -2
  24. package/dist/{preset-map-OJm5IWuL.mjs → preset-map-C1UwEald.mjs} +3 -1
  25. package/dist/{preset-map-C3jxnkiX.cjs → preset-map-CNBOeqAu.cjs} +3 -1
  26. package/dist/{presets-2I68Ipyl.cjs → presets-BPVVlfI2.cjs} +93 -23
  27. package/dist/{presets-DOGXQzYT.mjs → presets-DVLDrPC-.mjs} +86 -22
  28. package/dist/presets.cjs +2 -1
  29. package/dist/presets.d.cts +2 -2
  30. package/dist/presets.d.mts +2 -2
  31. package/dist/presets.mjs +2 -2
  32. package/dist/setup.cjs +71 -13
  33. package/dist/setup.mjs +69 -11
  34. package/docs/migrating-from-jest.md +6 -4
  35. package/docs/migrating-from-vitest-react-native.md +6 -3
  36. package/docs/release-readiness.md +52 -0
  37. package/package.json +31 -20
package/dist/helpers.cjs CHANGED
@@ -11,9 +11,14 @@ function getMock() {
11
11
  if (!mock) throw new Error("vitest-native helpers called before setup. Ensure the vitest-native plugin is configured.");
12
12
  return mock;
13
13
  }
14
+ function getNativeControl() {
15
+ return globalThis.__vitest_native_control ?? null;
16
+ }
14
17
  /** The original NativeModules instance, stored so resetAllMocks() can restore it. */
15
18
  let originalNativeModules = null;
16
19
  function setPlatform(os) {
20
+ const native = getNativeControl();
21
+ if (native) return native.setPlatform(os);
17
22
  const platform = getMock().Platform;
18
23
  platform.OS = os;
19
24
  platform.Version = os === "ios" ? "17.0" : 34;
@@ -22,6 +27,8 @@ function setPlatform(os) {
22
27
  });
23
28
  }
24
29
  function setDimensions(dims) {
30
+ const native = getNativeControl();
31
+ if (native) return native.setDimensions(dims);
25
32
  const mock = getMock();
26
33
  mock.Dimensions.set({
27
34
  window: dims,
@@ -30,6 +37,8 @@ function setDimensions(dims) {
30
37
  if (mock.useWindowDimensions._setDimensions) mock.useWindowDimensions._setDimensions(dims);
31
38
  }
32
39
  function setColorScheme(scheme) {
40
+ const native = getNativeControl();
41
+ if (native) return native.setColorScheme(scheme);
33
42
  const mock = getMock();
34
43
  const resolved = scheme ?? "light";
35
44
  mock.Appearance.setColorScheme(resolved);
@@ -40,6 +49,8 @@ function setInsets(insets) {
40
49
  if (safeArea?._setInsets) safeArea._setInsets(insets);
41
50
  }
42
51
  function mockNativeModule(name, impl) {
52
+ const native = getNativeControl();
53
+ if (native) return native.mockNativeModule(name, impl);
43
54
  const mock = getMock();
44
55
  if (originalNativeModules === null) originalNativeModules = mock.NativeModules;
45
56
  const existing = mock.NativeModules;
@@ -61,6 +72,8 @@ function clearMockFns(obj, visited = /* @__PURE__ */ new Set()) {
61
72
  }
62
73
  }
63
74
  function resetAllMocks() {
75
+ const native = getNativeControl();
76
+ if (native) return native.resetAllMocks();
64
77
  const mock = getMock();
65
78
  clearMockFns(mock);
66
79
  mock.Platform.OS = "ios";
package/dist/helpers.mjs CHANGED
@@ -10,9 +10,14 @@ function getMock() {
10
10
  if (!mock) throw new Error("vitest-native helpers called before setup. Ensure the vitest-native plugin is configured.");
11
11
  return mock;
12
12
  }
13
+ function getNativeControl() {
14
+ return globalThis.__vitest_native_control ?? null;
15
+ }
13
16
  /** The original NativeModules instance, stored so resetAllMocks() can restore it. */
14
17
  let originalNativeModules = null;
15
18
  function setPlatform(os) {
19
+ const native = getNativeControl();
20
+ if (native) return native.setPlatform(os);
16
21
  const platform = getMock().Platform;
17
22
  platform.OS = os;
18
23
  platform.Version = os === "ios" ? "17.0" : 34;
@@ -21,6 +26,8 @@ function setPlatform(os) {
21
26
  });
22
27
  }
23
28
  function setDimensions(dims) {
29
+ const native = getNativeControl();
30
+ if (native) return native.setDimensions(dims);
24
31
  const mock = getMock();
25
32
  mock.Dimensions.set({
26
33
  window: dims,
@@ -29,6 +36,8 @@ function setDimensions(dims) {
29
36
  if (mock.useWindowDimensions._setDimensions) mock.useWindowDimensions._setDimensions(dims);
30
37
  }
31
38
  function setColorScheme(scheme) {
39
+ const native = getNativeControl();
40
+ if (native) return native.setColorScheme(scheme);
32
41
  const mock = getMock();
33
42
  const resolved = scheme ?? "light";
34
43
  mock.Appearance.setColorScheme(resolved);
@@ -39,6 +48,8 @@ function setInsets(insets) {
39
48
  if (safeArea?._setInsets) safeArea._setInsets(insets);
40
49
  }
41
50
  function mockNativeModule(name, impl) {
51
+ const native = getNativeControl();
52
+ if (native) return native.mockNativeModule(name, impl);
42
53
  const mock = getMock();
43
54
  if (originalNativeModules === null) originalNativeModules = mock.NativeModules;
44
55
  const existing = mock.NativeModules;
@@ -60,6 +71,8 @@ function clearMockFns(obj, visited = /* @__PURE__ */ new Set()) {
60
71
  }
61
72
  }
62
73
  function resetAllMocks() {
74
+ const native = getNativeControl();
75
+ if (native) return native.resetAllMocks();
63
76
  const mock = getMock();
64
77
  clearMockFns(mock);
65
78
  mock.Platform.OS = "ios";
@@ -1,7 +1,5 @@
1
1
  import { Mock } from "vitest";
2
2
 
3
- //#region \0rolldown/runtime.js
4
- //#endregion
5
3
  //#region src/types.d.ts
6
4
  /** Static methods available on the Image component mock. */
7
5
  interface ImageStatic {
@@ -211,10 +209,9 @@ interface VitestNativeOptions {
211
209
  * Test engine.
212
210
  * - 'mock' — pure-JS reimplementation of React Native (fastest, lower fidelity).
213
211
  * - 'native' — runs real React Native JS, mocking only the native boundary
214
- * (Jest-level fidelity).
215
- * - 'auto' — picks automatically. Currently resolves to 'mock'; when
216
- * '@react-native/babel-preset' is present it recommends 'native'
217
- * (becomes the default in v1).
212
+ * (highest fidelity).
213
+ * - 'auto' — resolves to 'native' when '@react-native/babel-preset' and
214
+ * '@babel/core' are available, otherwise falls back to 'mock'.
218
215
  * Default: 'auto'.
219
216
  */
220
217
  engine?: "auto" | "mock" | "native";
@@ -235,7 +232,8 @@ interface VitestNativeOptions {
235
232
  */
236
233
  presets?: Preset[];
237
234
  /**
238
- * Plain-data overrides merged into the react-native module mock.
235
+ * `engine: 'mock'` only. Plain-data overrides merged into the react-native
236
+ * module mock.
239
237
  * Values must be JSON-serializable (strings, numbers, booleans, plain
240
238
  * objects, arrays). Function values are not supported — use vi.mock()
241
239
  * in a setup file for function-based overrides.
@@ -273,15 +271,21 @@ interface VitestNativeOptions {
273
271
  *
274
272
  * Pass an object to tune worker recycling (self-defense against suites that
275
273
  * leak process-wide resources the per-file reset can't reclaim):
276
- * - `recycleAfterFiles`: retire a worker after it has run N test files.
277
- * - `memoryLimit`: retire a worker when its JS heap (bytes) after a test
278
- * file meets or exceeds this value.
274
+ * - `recycleAfterFiles`: retire a worker after it has run N test files. This
275
+ * is enforced between Vitest scheduler tasks; a single task containing
276
+ * multiple files cannot be interrupted.
277
+ * - `memoryLimit`: retire a worker when its reported JS heap (bytes) meets
278
+ * or exceeds this value, also between scheduler tasks.
279
+ * - `preserveGlobals`: exact globalThis property names intentionally owned
280
+ * by resident external libraries. App/test globals are otherwise removed
281
+ * between files. Storybook's preview registry is preserved automatically.
279
282
  *
280
283
  * Default: false (each file runs in a fresh worker; RN reloads per file).
281
284
  */
282
285
  hotRuntime?: boolean | {
283
286
  recycleAfterFiles?: number;
284
287
  memoryLimit?: number;
288
+ preserveGlobals?: string[];
285
289
  };
286
290
  }
287
291
  //#endregion
@@ -317,8 +321,11 @@ declare function svg(): Preset;
317
321
  //#endregion
318
322
  //#region src/presets/webview.d.ts
319
323
  declare function webview(): Preset;
324
+ //#endregion
325
+ //#region src/presets/vector-icons.d.ts
326
+ declare function vectorIcons(): Preset;
320
327
  declare namespace index_d_exports {
321
- export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, webview };
328
+ export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
322
329
  }
323
330
  //#endregion
324
- export { deviceInfo as a, asyncStorage as c, gestureHandler as d, reanimated as f, VitestNativeOptions as h, mmkv as i, navigation as l, ReactNativeMock as m, webview as n, expo as o, Preset as p, svg as r, screens as s, index_d_exports as t, safeAreaContext as u };
331
+ export { mmkv as a, screens as c, safeAreaContext as d, gestureHandler as f, VitestNativeOptions as g, ReactNativeMock as h, svg as i, asyncStorage as l, Preset as m, vectorIcons as n, deviceInfo as o, reanimated as p, webview as r, expo as s, index_d_exports as t, navigation as u };
@@ -1,5 +1,7 @@
1
1
  import { Mock } from "vitest";
2
2
 
3
+ //#region \0rolldown/runtime.js
4
+ //#endregion
3
5
  //#region src/types.d.ts
4
6
  /** Static methods available on the Image component mock. */
5
7
  interface ImageStatic {
@@ -209,10 +211,9 @@ interface VitestNativeOptions {
209
211
  * Test engine.
210
212
  * - 'mock' — pure-JS reimplementation of React Native (fastest, lower fidelity).
211
213
  * - 'native' — runs real React Native JS, mocking only the native boundary
212
- * (Jest-level fidelity).
213
- * - 'auto' — picks automatically. Currently resolves to 'mock'; when
214
- * '@react-native/babel-preset' is present it recommends 'native'
215
- * (becomes the default in v1).
214
+ * (highest fidelity).
215
+ * - 'auto' — resolves to 'native' when '@react-native/babel-preset' and
216
+ * '@babel/core' are available, otherwise falls back to 'mock'.
216
217
  * Default: 'auto'.
217
218
  */
218
219
  engine?: "auto" | "mock" | "native";
@@ -233,7 +234,8 @@ interface VitestNativeOptions {
233
234
  */
234
235
  presets?: Preset[];
235
236
  /**
236
- * Plain-data overrides merged into the react-native module mock.
237
+ * `engine: 'mock'` only. Plain-data overrides merged into the react-native
238
+ * module mock.
237
239
  * Values must be JSON-serializable (strings, numbers, booleans, plain
238
240
  * objects, arrays). Function values are not supported — use vi.mock()
239
241
  * in a setup file for function-based overrides.
@@ -271,15 +273,21 @@ interface VitestNativeOptions {
271
273
  *
272
274
  * Pass an object to tune worker recycling (self-defense against suites that
273
275
  * leak process-wide resources the per-file reset can't reclaim):
274
- * - `recycleAfterFiles`: retire a worker after it has run N test files.
275
- * - `memoryLimit`: retire a worker when its JS heap (bytes) after a test
276
- * file meets or exceeds this value.
276
+ * - `recycleAfterFiles`: retire a worker after it has run N test files. This
277
+ * is enforced between Vitest scheduler tasks; a single task containing
278
+ * multiple files cannot be interrupted.
279
+ * - `memoryLimit`: retire a worker when its reported JS heap (bytes) meets
280
+ * or exceeds this value, also between scheduler tasks.
281
+ * - `preserveGlobals`: exact globalThis property names intentionally owned
282
+ * by resident external libraries. App/test globals are otherwise removed
283
+ * between files. Storybook's preview registry is preserved automatically.
277
284
  *
278
285
  * Default: false (each file runs in a fresh worker; RN reloads per file).
279
286
  */
280
287
  hotRuntime?: boolean | {
281
288
  recycleAfterFiles?: number;
282
289
  memoryLimit?: number;
290
+ preserveGlobals?: string[];
283
291
  };
284
292
  }
285
293
  //#endregion
@@ -315,8 +323,11 @@ declare function svg(): Preset;
315
323
  //#endregion
316
324
  //#region src/presets/webview.d.ts
317
325
  declare function webview(): Preset;
326
+ //#endregion
327
+ //#region src/presets/vector-icons.d.ts
328
+ declare function vectorIcons(): Preset;
318
329
  declare namespace index_d_exports {
319
- export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, webview };
330
+ export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
320
331
  }
321
332
  //#endregion
322
- export { deviceInfo as a, asyncStorage as c, gestureHandler as d, reanimated as f, VitestNativeOptions as h, mmkv as i, navigation as l, ReactNativeMock as m, webview as n, expo as o, Preset as p, svg as r, screens as s, index_d_exports as t, safeAreaContext as u };
333
+ export { mmkv as a, screens as c, safeAreaContext as d, gestureHandler as f, VitestNativeOptions as g, ReactNativeMock as h, svg as i, asyncStorage as l, Preset as m, vectorIcons as n, deviceInfo as o, reanimated as p, webview as r, expo as s, index_d_exports as t, navigation as u };
package/dist/index.cjs CHANGED
@@ -1,15 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("./chunk-CZWwpsFl.cjs");
3
- const require_preset_map = require("./preset-map-C3jxnkiX.cjs");
4
- const require_presets = require("./presets-2I68Ipyl.cjs");
3
+ const require_preset_map = require("./preset-map-CNBOeqAu.cjs");
4
+ const require_presets = require("./presets-BPVVlfI2.cjs");
5
5
  let node_url = require("node:url");
6
6
  let node_path = require("node:path");
7
- node_path = require_chunk.__toESM(node_path);
7
+ node_path = require_chunk.__toESM(node_path, 1);
8
8
  let node_fs = require("node:fs");
9
- node_fs = require_chunk.__toESM(node_fs);
9
+ node_fs = require_chunk.__toESM(node_fs, 1);
10
10
  let node_module = require("node:module");
11
11
  let flow_remove_types = require("flow-remove-types");
12
- flow_remove_types = require_chunk.__toESM(flow_remove_types);
12
+ flow_remove_types = require_chunk.__toESM(flow_remove_types, 1);
13
13
  //#region src/resolve.ts
14
14
  const PLATFORM_EXTENSIONS_IOS = [
15
15
  ".ios.tsx",
@@ -54,6 +54,34 @@ const KNOWN_OPTIONS = [
54
54
  "transform",
55
55
  "hotRuntime"
56
56
  ];
57
+ const KNOWN_HOT_RUNTIME_OPTIONS = [
58
+ "recycleAfterFiles",
59
+ "memoryLimit",
60
+ "preserveGlobals"
61
+ ];
62
+ function assertStringArray(value, option) {
63
+ 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.`);
64
+ }
65
+ function assertNonNegativeInteger(value, option) {
66
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new TypeError(`[vitest-native] "${option}" must be a non-negative safe integer.`);
67
+ }
68
+ function validateOptions(options) {
69
+ 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".`);
70
+ if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new TypeError(`[vitest-native] "platform" must be "ios" or "android".`);
71
+ if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new TypeError(`[vitest-native] "diagnostics" must be a boolean.`);
72
+ if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
73
+ if (options.transform !== void 0) assertStringArray(options.transform, "transform");
74
+ if (options.presets !== void 0 && !Array.isArray(options.presets)) throw new TypeError(`[vitest-native] "presets" must be an array.`);
75
+ 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.`);
76
+ const hotRuntime = options.hotRuntime;
77
+ if (hotRuntime === void 0 || typeof hotRuntime === "boolean") return;
78
+ if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new TypeError(`[vitest-native] "hotRuntime" must be a boolean or an options object.`);
79
+ const hotOptions = hotRuntime;
80
+ for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) throw new TypeError(`[vitest-native] Unknown hotRuntime option "${key}".`);
81
+ if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
82
+ if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
83
+ if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
84
+ }
57
85
  function satisfiesMinimum(version, minimum) {
58
86
  const parse = (v) => v.replace(/^[^0-9]*/, "").split(".").map(Number);
59
87
  const [aMaj, aMin = 0, aPat = 0] = parse(version);
@@ -62,11 +90,14 @@ function satisfiesMinimum(version, minimum) {
62
90
  if (aMin !== bMin) return aMin > bMin;
63
91
  return aPat >= bPat;
64
92
  }
65
- function validatePeerDependency(pkgName, minimumVersion, projectRoot) {
93
+ function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
66
94
  const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
67
95
  try {
68
96
  const { version } = req(req.resolve(`${pkgName}/package.json`));
69
- if (!satisfiesMinimum(version, minimumVersion)) return `vitest-native requires ${pkgName} >= ${minimumVersion}, but found ${version}. Please upgrade.`;
97
+ const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
98
+ const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
99
+ if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
100
+ if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
70
101
  return null;
71
102
  } catch {
72
103
  return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
@@ -111,29 +142,19 @@ function levenshtein(a, b) {
111
142
  function escapeRe(s) {
112
143
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
113
144
  }
114
- function nativeEngineConfig(setupFilePath, env, transformPkgs = [], hot) {
145
+ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }) {
115
146
  const extraExternal = transformPkgs.map((p) => new RegExp(`[\\\\/]${escapeRe(p)}[\\\\/]`));
116
147
  const fullEnv = { ...env };
117
148
  if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
118
149
  return {
119
- esbuild: { jsx: "automatic" },
150
+ ...jsxTransform,
120
151
  resolve: {
121
152
  conditions: ["react-native"],
122
- extensions: [
123
- ".ios.tsx",
124
- ".ios.ts",
125
- ".ios.js",
126
- ".native.tsx",
127
- ".native.ts",
128
- ".native.js",
129
- ".tsx",
130
- ".ts",
131
- ".jsx",
132
- ".js"
133
- ],
153
+ extensions,
134
154
  dedupe: [
135
155
  "react",
136
156
  "react-test-renderer",
157
+ "test-renderer",
137
158
  "react-is"
138
159
  ]
139
160
  },
@@ -225,6 +246,7 @@ function stripFsPrefix(id) {
225
246
  }
226
247
  async function autoDetectPresets(diagnostics, projectRoot) {
227
248
  const detected = [];
249
+ const enabled = /* @__PURE__ */ new Set();
228
250
  const presetFactories = await Promise.resolve().then(() => require("./presets.cjs"));
229
251
  const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
230
252
  for (const [pkgName, exportName] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) {
@@ -234,15 +256,39 @@ async function autoDetectPresets(diagnostics, projectRoot) {
234
256
  installed = true;
235
257
  } catch {}
236
258
  if (installed) {
259
+ if (enabled.has(exportName)) continue;
237
260
  const factory = presetFactories[exportName];
238
261
  if (typeof factory === "function") {
239
262
  detected.push(factory());
263
+ enabled.add(exportName);
240
264
  if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
241
265
  }
242
266
  } else if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
243
267
  }
244
268
  return detected;
245
269
  }
270
+ function resolvePackageVersion(packageName, projectRoot) {
271
+ const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
272
+ try {
273
+ return req(`${packageName}/package.json`).version ?? null;
274
+ } catch {
275
+ return null;
276
+ }
277
+ }
278
+ function getJsxTransformConfig(projectRoot) {
279
+ const viteVersion = resolvePackageVersion("vite", projectRoot);
280
+ return Number(viteVersion?.split(".")[0]) >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
281
+ }
282
+ /**
283
+ * Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
284
+ * `esbuild.jsx` before Vite 8 and `oxc.jsx` from Vite 8 onward. The runtime
285
+ * version check above guarantees that only the matching shape is returned,
286
+ * but a build against any single Vite major cannot type the other major's
287
+ * valid config. Keep that unavoidable assertion at this compatibility edge.
288
+ */
289
+ function asCompatibleViteConfig(config) {
290
+ return config;
291
+ }
246
292
  /**
247
293
  * Synchronously resolve the export-names of presets whose package is installed.
248
294
  * Used by the native-engine config path (which can't await the factory imports)
@@ -384,8 +430,11 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
384
430
  * React Native code in a Node/JSDOM environment.
385
431
  */
386
432
  function reactNative(options) {
433
+ if (options) {
434
+ validateOptions(options);
435
+ warnUnknownOptions(options);
436
+ }
387
437
  if (options?.mocks && containsFunctions(options.mocks)) throw new Error("[vitest-native] The \"mocks\" option contains function values, which cannot be transferred to Vitest worker processes. Only JSON-serializable values (strings, numbers, booleans, plain objects, arrays) are supported.\n\nFor function-based mock overrides, use vi.mock() in a setup file:\n\n // vitest.setup.ts\n import { vi } from 'vitest';\n vi.mock('react-native', async (importOriginal) => {\n const actual = await importOriginal();\n return { ...actual, Alert: { alert: vi.fn() } };\n });");
388
- if (options) warnUnknownOptions(options);
389
438
  let resolved;
390
439
  const presetModules = /* @__PURE__ */ new Map();
391
440
  const presetExportNames = /* @__PURE__ */ new Map();
@@ -415,6 +464,7 @@ function reactNative(options) {
415
464
  enforce: "pre",
416
465
  async config(userConfig, _env) {
417
466
  const resolvedRoot = userConfig.root ? node_path.default.resolve(userConfig.root) : process.cwd();
467
+ const jsxTransform = getJsxTransformConfig(resolvedRoot);
418
468
  const decision = detectEngine(requestedEngine, resolvedRoot);
419
469
  engine = decision.engine;
420
470
  if (decision.notice) console.log(decision.notice);
@@ -423,29 +473,36 @@ function reactNative(options) {
423
473
  VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
424
474
  VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
425
475
  };
476
+ const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
477
+ if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
478
+ env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify([...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))]);
479
+ if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
426
480
  if (engine === "native") {
481
+ 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'.");
427
482
  const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
428
483
  if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
429
- return nativeEngineConfig(nativeSetupPath, env, transformPkgs, hotRuntime ? {
430
- pool: (await Promise.resolve().then(() => require("./pool-B4mWN3N5.cjs"))).nativePool({
484
+ return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hotRuntime ? {
485
+ pool: (await Promise.resolve().then(() => require("./pool-p54QV1dQ.cjs"))).nativePool({
431
486
  workerEntry: nativeWorkerPath,
432
487
  recycleAfterFiles: hotRecycle.recycleAfterFiles,
433
- memoryLimit: hotRecycle.memoryLimit
488
+ memoryLimit: hotRecycle.memoryLimit,
489
+ diagnostics
434
490
  }),
435
491
  runnerPath: nativeRunnerPath
436
- } : void 0);
492
+ } : void 0, jsxTransform));
437
493
  }
438
494
  if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
439
495
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
440
496
  if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
441
- return {
442
- esbuild: { jsx: "automatic" },
497
+ return asCompatibleViteConfig({
498
+ ...jsxTransform,
443
499
  resolve: {
444
500
  extensions,
445
501
  conditions: ["react-native"],
446
502
  dedupe: [
447
503
  "react",
448
504
  "react-test-renderer",
505
+ "test-renderer",
449
506
  "react-is"
450
507
  ]
451
508
  },
@@ -453,27 +510,37 @@ function reactNative(options) {
453
510
  setupFiles: [setupFilePath],
454
511
  env
455
512
  }
456
- };
513
+ });
457
514
  },
458
515
  async configResolved(config) {
459
- for (const { name, range } of [
516
+ const peers = [
460
517
  {
461
518
  name: "vitest",
462
- range: "4.0.0"
519
+ minimum: "4.0.0",
520
+ maximumMajor: 5
463
521
  },
464
522
  {
465
523
  name: "vite",
466
- range: "5.0.0"
524
+ minimum: "6.4.2",
525
+ maximumMajor: 9,
526
+ minimumByMajor: {
527
+ 6: "6.4.2",
528
+ 7: "7.3.2",
529
+ 8: "8.0.5"
530
+ }
467
531
  },
468
532
  {
469
533
  name: "react",
470
- range: "18.0.0"
534
+ minimum: "18.0.0"
471
535
  }
472
- ]) {
473
- const error = validatePeerDependency(name, range, config.root);
474
- if (error) console.error(`[vitest-native] ${error}`);
536
+ ];
537
+ const peerErrors = [];
538
+ for (const { name, minimum, maximumMajor, minimumByMajor } of peers) {
539
+ const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
540
+ if (error) peerErrors.push(error);
475
541
  }
476
- const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root);
542
+ if (peerErrors.length > 0) throw new Error(`[vitest-native] Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
543
+ const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root, 15);
477
544
  if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
478
545
  resolved = await resolveOptions(options, config.root);
479
546
  resolved.engine = engine;
@@ -528,6 +595,8 @@ function reactNative(options) {
528
595
  virtualCodeCache.set(id, code);
529
596
  return code;
530
597
  }
598
+ const fsPath = stripFsPrefix(id);
599
+ if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
531
600
  if (engine === "native") return void 0;
532
601
  if (id === "\0virtual:react-native") return "export default {};";
533
602
  if (id.startsWith("\0virtual:rn-subpath:")) {
@@ -542,8 +611,6 @@ function reactNative(options) {
542
611
  }
543
612
  return code;
544
613
  }
545
- const fsPath = stripFsPrefix(id);
546
- if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
547
614
  },
548
615
  transform(code, id) {
549
616
  if (engine === "native") return void 0;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { h as VitestNativeOptions, m as ReactNativeMock, p as Preset, t as index_d_exports } from "./index-DEB7OFaJ.cjs";
1
+ import { g as VitestNativeOptions, h as ReactNativeMock, m as Preset, t as index_d_exports } from "./index-Dr3WvKWI.cjs";
2
2
  import { Plugin } from "vite";
3
3
 
4
4
  //#region src/plugin.d.ts
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { h as VitestNativeOptions, m as ReactNativeMock, p as Preset, t as index_d_exports } from "./index-CJIhukN_.mjs";
1
+ import { g as VitestNativeOptions, h as ReactNativeMock, m as Preset, t as index_d_exports } from "./index-DGNLmGjq.mjs";
2
2
  import { Plugin } from "vite";
3
3
 
4
4
  //#region src/plugin.d.ts