vitest-native 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # vitest-native
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 37c8123: Native engine: Metro-style resolution for externalized node_modules packages, plus navigation route params and jest-compat timer leniency
8
+
9
+ Vitest externalizes most `node_modules` dependencies (any that Node can import
10
+ natively), so they load through Node rather than Vite — and Node's resolver has no
11
+ notion of React Native's Metro conventions. The native engine now fills those gaps
12
+ for externalized packages:
13
+
14
+ - **Platform extensions** — `import './x'` resolves `x.native.js` / `x.ios.js` /
15
+ `x.android.js` over the default `x.js`, for any `node_modules` package (matching
16
+ Metro and Vite's behavior for inlined code). Previously only `react-native` and
17
+ packages in `transform` got this, so e.g. `@react-navigation` silently loaded its
18
+ web variant (`useLinking.js`), breaking the navigation lifecycle with no error.
19
+ - **Asset imports** — `import icon from './icon.png'` (and other asset extensions)
20
+ resolve to the basename string instead of throwing "Unknown file extension" in
21
+ Node's ESM loader.
22
+ - **JSON imports** — `import data from './data.json'` without a `with { type: 'json' }`
23
+ attribute no longer throws `ERR_IMPORT_ATTRIBUTE_MISSING` on Node 22+. The native
24
+ engine injects the attribute so Node's own JSON module loader handles it.
25
+
26
+ Other changes:
27
+
28
+ - **`navigation` preset** accepts `defaultRouteParams`, used by the mocked
29
+ `useRoute().params` (and as a `<Screen>`'s fallback params) — so components that
30
+ read route params at mount can be tested without a custom `vi.mock`.
31
+ - **jest-compat** `jest.advanceTimersByTime` / `advanceTimersByTimeAsync` are now
32
+ no-ops when fake timers are inactive, matching Jest's lenient behavior (Vitest's
33
+ `vi` throws). This fixes RNTL `userEvent.setup({ advanceTimers })` on suites that
34
+ never enable fake timers. All other `jest` methods continue to forward to `vi`.
35
+
36
+ ### Patch Changes
37
+
38
+ - 5a86872: Add mocks for react-native 0.86 top-level exports
39
+
40
+ The weekly compatibility check flagged new stable exports in react-native 0.86.
41
+ `EventEmitter`, `useAnimatedColor`, and `useAnimatedValueXY` are now mocked so
42
+ named imports resolve under the mock engine. The experimental virtualized-collection
43
+ API (`unstable_VirtualRow`, `unstable_createVirtualCollectionView`, and related)
44
+ is added to the compatibility check's known-skipped list.
45
+
46
+ ## 0.6.1
47
+
48
+ ### Patch Changes
49
+
50
+ - 40a5147: Native engine: fix `import { Appearance } from 'react-native'` (and other lazy-getter RN exports) failing with "does not provide an export named …" when the import comes from an **externalized ESM dependency**.
51
+
52
+ React Native's index exposes everything via lazy getters (`module.exports = { get Appearance() {…} }`), which `cjs-module-lexer` can't surface as named exports when Node imports the CommonJS module from the ESM graph. The Node ESM loader now serves RN's main index as a thin re-export of the real (Flow-stripped) module plus a `cjs-module-lexer`-recognized export hint, so named imports resolve while the real getters stay lazy (no eager load of RN's surface). The `require('react-native')` path is unchanged.
53
+
54
+ Previously this needed a manual `transform: ['the-lib']` workaround (e.g. for `uniwind`); that's no longer required. Surfaced by the obytes-template bake-off.
55
+
3
56
  ## 0.6.0
4
57
 
5
58
  ### Minor Changes
package/README.md CHANGED
@@ -573,6 +573,41 @@ preset.
573
573
  Real RN computes host props (e.g. `<Text>`'s `accessible`, `allowFontScaling`) that mocks omit, so
574
574
  the tree is richer. Re-record once with `npx vitest -u` after migrating.
575
575
 
576
+ **`Worker terminated due to reaching memory limit` / `JS heap out of memory` (large native suites)**
577
+ Every test file that renders real React Native loads a full renderer, so a large suite can grow a
578
+ worker's heap past Node's default ceiling. Cap it with Vitest's per-worker limit — Vitest recycles a
579
+ worker once its heap exceeds the limit, so growth never reaches the hard OOM:
580
+
581
+ ```ts
582
+ // vitest.config.ts
583
+ export default defineConfig({
584
+ test: { poolOptions: { threads: { memoryLimit: "512MB" } } },
585
+ });
586
+ ```
587
+
588
+ The experimental `reactNative({ hotRuntime: true })` also helps: it keeps React Native resident
589
+ across files (loaded once per worker instead of per file) and recycles workers on a memory/file
590
+ budget.
591
+
592
+ **`Vitest caught N unhandled errors` in error-boundary tests**
593
+ A test that intentionally throws inside a component (to exercise an error boundary) makes React log
594
+ a "recovered from an error during concurrent rendering" message and Vitest count it — even though
595
+ the boundary worked and the test passes. It's cosmetic and the assertions are unaffected. Silence it
596
+ in a setup file if you like (e.g. filter the message in an `onConsoleLog`/`console.error` wrapper).
597
+
598
+ **Overriding a preset's mock (e.g. navigation route params)**
599
+ Auto-detected presets shadow a library with a built-in mock. To change what that mock returns for a
600
+ test or project, `vi.mock` the module in a setup file and spread the preset's mock — presets expose
601
+ the module to Vitest's graph, so `vi.mock` applies and `importOriginal()` returns the preset mock:
602
+
603
+ ```ts
604
+ // vitest.setup.ts
605
+ vi.mock("@react-navigation/native", async (importOriginal) => ({
606
+ ...(await importOriginal()),
607
+ useRoute: () => ({ key: "r", name: "Screen", params: { id: "1" } }),
608
+ }));
609
+ ```
610
+
576
611
  ---
577
612
 
578
613
  ## RNTL Matchers
@@ -739,6 +774,14 @@ export default defineConfig({
739
774
  });
740
775
  ```
741
776
 
777
+ Platform resolution applies both to your app/test code (resolved by Vite) **and** to
778
+ third-party `node_modules` packages with platform-specific files (e.g.
779
+ `@react-navigation`'s `useLinking.native.js`). The latter matters because Vitest
780
+ externalizes most `node_modules` dependencies — they load through Node, whose resolver
781
+ has no notion of `.native.js`. The native engine fills that gap so externalized packages
782
+ resolve the same `.native`/`.ios`/`.android` variant Metro would, instead of silently
783
+ falling back to the default (often web) file.
784
+
742
785
  ---
743
786
 
744
787
  ## Asset Stubs
@@ -162,6 +162,7 @@ interface ReactNativeMock {
162
162
  UIManager: Record<string, any>;
163
163
  NativeEventEmitter: new (...args: any[]) => any;
164
164
  NativeAppEventEmitter: Record<string, any>;
165
+ EventEmitter: new (...args: any[]) => any;
165
166
  NativeComponentRegistry: Record<string, any>;
166
167
  requireNativeComponent: Mock;
167
168
  AppRegistry: Record<string, Mock>;
@@ -174,6 +175,8 @@ interface ReactNativeMock {
174
175
  Settings: Record<string, Mock>;
175
176
  DeviceInfo: Record<string, any>;
176
177
  useAnimatedValue: Mock;
178
+ useAnimatedValueXY: Mock;
179
+ useAnimatedColor: Mock;
177
180
  RootTagContext: React.Context<any>;
178
181
  ReactNativeVersion: {
179
182
  major: number;
@@ -203,6 +206,29 @@ interface PresetModule {
203
206
  interface Preset {
204
207
  name: string;
205
208
  modules: Record<string, PresetModule>;
209
+ /**
210
+ * Optional JSON-serializable configuration for the preset. Presets are rebuilt
211
+ * inside Vitest worker processes from their `name`, so any options passed to a
212
+ * preset factory (e.g. `navigation({ defaultRouteParams })`) must be carried
213
+ * here to survive the main-process → worker boundary. Read by the native setup
214
+ * file and passed back into the factory in-worker. Must be JSON-serializable.
215
+ */
216
+ config?: Record<string, unknown>;
217
+ }
218
+ /** Options for the `navigation` preset. */
219
+ interface NavigationPresetOptions {
220
+ /**
221
+ * Params returned by the mocked `useRoute().params` (and used as a `<Screen>`'s
222
+ * fallback `initialParams`). Lets you test components that read route params at
223
+ * mount — e.g. `useRoute().params.id` — without a custom `vi.mock`. Must be
224
+ * JSON-serializable (it crosses the worker boundary).
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * presets.navigation({ defaultRouteParams: { id: '1', mode: 'edit' } })
229
+ * ```
230
+ */
231
+ defaultRouteParams?: Record<string, unknown>;
206
232
  }
207
233
  interface VitestNativeOptions {
208
234
  /** Target platform. Default: 'ios' */
@@ -301,7 +327,7 @@ declare function gestureHandler(): Preset;
301
327
  declare function safeAreaContext(): Preset;
302
328
  //#endregion
303
329
  //#region src/presets/navigation.d.ts
304
- declare function navigation(): Preset;
330
+ declare function navigation(presetOptions?: NavigationPresetOptions): Preset;
305
331
  //#endregion
306
332
  //#region src/presets/async-storage.d.ts
307
333
  declare function asyncStorage(): Preset;
@@ -160,6 +160,7 @@ interface ReactNativeMock {
160
160
  UIManager: Record<string, any>;
161
161
  NativeEventEmitter: new (...args: any[]) => any;
162
162
  NativeAppEventEmitter: Record<string, any>;
163
+ EventEmitter: new (...args: any[]) => any;
163
164
  NativeComponentRegistry: Record<string, any>;
164
165
  requireNativeComponent: Mock;
165
166
  AppRegistry: Record<string, Mock>;
@@ -172,6 +173,8 @@ interface ReactNativeMock {
172
173
  Settings: Record<string, Mock>;
173
174
  DeviceInfo: Record<string, any>;
174
175
  useAnimatedValue: Mock;
176
+ useAnimatedValueXY: Mock;
177
+ useAnimatedColor: Mock;
175
178
  RootTagContext: React.Context<any>;
176
179
  ReactNativeVersion: {
177
180
  major: number;
@@ -201,6 +204,29 @@ interface PresetModule {
201
204
  interface Preset {
202
205
  name: string;
203
206
  modules: Record<string, PresetModule>;
207
+ /**
208
+ * Optional JSON-serializable configuration for the preset. Presets are rebuilt
209
+ * inside Vitest worker processes from their `name`, so any options passed to a
210
+ * preset factory (e.g. `navigation({ defaultRouteParams })`) must be carried
211
+ * here to survive the main-process → worker boundary. Read by the native setup
212
+ * file and passed back into the factory in-worker. Must be JSON-serializable.
213
+ */
214
+ config?: Record<string, unknown>;
215
+ }
216
+ /** Options for the `navigation` preset. */
217
+ interface NavigationPresetOptions {
218
+ /**
219
+ * Params returned by the mocked `useRoute().params` (and used as a `<Screen>`'s
220
+ * fallback `initialParams`). Lets you test components that read route params at
221
+ * mount — e.g. `useRoute().params.id` — without a custom `vi.mock`. Must be
222
+ * JSON-serializable (it crosses the worker boundary).
223
+ *
224
+ * @example
225
+ * ```ts
226
+ * presets.navigation({ defaultRouteParams: { id: '1', mode: 'edit' } })
227
+ * ```
228
+ */
229
+ defaultRouteParams?: Record<string, unknown>;
204
230
  }
205
231
  interface VitestNativeOptions {
206
232
  /** Target platform. Default: 'ios' */
@@ -299,7 +325,7 @@ declare function gestureHandler(): Preset;
299
325
  declare function safeAreaContext(): Preset;
300
326
  //#endregion
301
327
  //#region src/presets/navigation.d.ts
302
- declare function navigation(): Preset;
328
+ declare function navigation(presetOptions?: NavigationPresetOptions): Preset;
303
329
  //#endregion
304
330
  //#region src/presets/async-storage.d.ts
305
331
  declare function asyncStorage(): Preset;
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("./chunk-CZWwpsFl.cjs");
3
3
  const require_preset_map = require("./preset-map-CNBOeqAu.cjs");
4
- const require_presets = require("./presets-BPVVlfI2.cjs");
4
+ const require_presets = require("./presets-BTG8fiNF.cjs");
5
5
  let node_url = require("node:url");
6
6
  let node_path = require("node:path");
7
7
  node_path = require_chunk.__toESM(node_path, 1);
@@ -386,6 +386,7 @@ const RN_EXPORT_NAMES = [
386
386
  "UIManager",
387
387
  "NativeEventEmitter",
388
388
  "NativeAppEventEmitter",
389
+ "EventEmitter",
389
390
  "NativeComponentRegistry",
390
391
  "requireNativeComponent",
391
392
  "AppRegistry",
@@ -398,6 +399,8 @@ const RN_EXPORT_NAMES = [
398
399
  "Settings",
399
400
  "DeviceInfo",
400
401
  "useAnimatedValue",
402
+ "useAnimatedValueXY",
403
+ "useAnimatedColor",
401
404
  "RootTagContext",
402
405
  "ReactNativeVersion",
403
406
  "Systrace",
@@ -481,6 +484,11 @@ function reactNative(options) {
481
484
  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'.");
482
485
  const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
483
486
  if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
487
+ if (options?.presets) {
488
+ const presetConfig = {};
489
+ for (const p of options.presets) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
490
+ if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
491
+ }
484
492
  return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hotRuntime ? {
485
493
  pool: (await Promise.resolve().then(() => require("./pool-p54QV1dQ.cjs"))).nativePool({
486
494
  workerEntry: nativeWorkerPath,
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { g as VitestNativeOptions, h as ReactNativeMock, m as Preset, t as index_d_exports } from "./index-Dr3WvKWI.cjs";
1
+ import { g as VitestNativeOptions, h as ReactNativeMock, m as Preset, t as index_d_exports } from "./index-BgzErxHj.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 { g as VitestNativeOptions, h as ReactNativeMock, m as Preset, t as index_d_exports } from "./index-DGNLmGjq.mjs";
1
+ import { g as VitestNativeOptions, h as ReactNativeMock, m as Preset, t as index_d_exports } from "./index-DbfKy_bm.mjs";
2
2
  import { Plugin } from "vite";
3
3
 
4
4
  //#region src/plugin.d.ts
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as AUTO_DETECT_PRESETS } from "./preset-map-C1UwEald.mjs";
2
- import { t as presets_exports } from "./presets-DVLDrPC-.mjs";
2
+ import { t as presets_exports } from "./presets-BFuAMwYQ.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import path from "node:path";
@@ -381,6 +381,7 @@ const RN_EXPORT_NAMES = [
381
381
  "UIManager",
382
382
  "NativeEventEmitter",
383
383
  "NativeAppEventEmitter",
384
+ "EventEmitter",
384
385
  "NativeComponentRegistry",
385
386
  "requireNativeComponent",
386
387
  "AppRegistry",
@@ -393,6 +394,8 @@ const RN_EXPORT_NAMES = [
393
394
  "Settings",
394
395
  "DeviceInfo",
395
396
  "useAnimatedValue",
397
+ "useAnimatedValueXY",
398
+ "useAnimatedColor",
396
399
  "RootTagContext",
397
400
  "ReactNativeVersion",
398
401
  "Systrace",
@@ -476,6 +479,11 @@ function reactNative(options) {
476
479
  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'.");
477
480
  const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
478
481
  if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
482
+ if (options?.presets) {
483
+ const presetConfig = {};
484
+ for (const p of options.presets) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
485
+ if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
486
+ }
479
487
  return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hotRuntime ? {
480
488
  pool: (await import("./pool-B7LBfcMQ.mjs")).nativePool({
481
489
  workerEntry: nativeWorkerPath,
@@ -27,6 +27,21 @@ if (typeof vi.requireMock !== "function") vi.requireMock = (m) => require(m);
27
27
  // it at top level don't crash.
28
28
  if (typeof vi.setTimeout !== "function") vi.setTimeout = () => {};
29
29
 
30
+ // `jest.advanceTimersByTime(Async)` is lenient in Jest: when fake timers are NOT
31
+ // active it's effectively a no-op. Vitest's `vi.advanceTimersByTimeAsync` instead
32
+ // throws "timers are not mocked". RNTL's `userEvent.setup({ advanceTimers })`
33
+ // commonly receives this function and calls it even on suites that never enable
34
+ // fake timers. Guard the two advance methods on `vi` itself (this file already
35
+ // extends `vi` above) to match Jest's leniency — done on `vi` rather than a wrapper
36
+ // so `globalThis.jest`, the `@jest/globals` shim (which exports `vi` as `jest`), and
37
+ // direct `vi` usage stay the same object.
38
+ const advanceTimersByTime = vi.advanceTimersByTime.bind(vi);
39
+ const advanceTimersByTimeAsync = vi.advanceTimersByTimeAsync.bind(vi);
40
+ vi.advanceTimersByTime = (...args) =>
41
+ vi.isFakeTimers() ? advanceTimersByTime(...args) : undefined;
42
+ vi.advanceTimersByTimeAsync = async (...args) =>
43
+ vi.isFakeTimers() ? advanceTimersByTimeAsync(...args) : undefined;
44
+
30
45
  globalThis.jest = vi;
31
46
 
32
47
  // jest.mock factories are wrapped by jestMockTransform to route their return
@@ -9,6 +9,11 @@ import { resolvePlatformFile } from "./resolve.mjs";
9
9
  import { buildPkgMatcher } from "./match.mjs";
10
10
 
11
11
  const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
12
+ // Any file under a node_modules directory. Platform-extension resolution
13
+ // (`.native.js` etc.) applies to every node_modules package, not just RN — matching
14
+ // Metro, which resolves platform variants project-wide. See loader.mjs for the
15
+ // ESM-path counterpart and the @react-navigation silent-failure this prevents.
16
+ const NODE_MODULES = /[\\/]node_modules[\\/]/;
12
17
 
13
18
  // Guarded via globalThis, not module scope: under the hot runtime this module
14
19
  // can be evaluated twice in one worker (once by the worker entry through Node's
@@ -66,7 +71,9 @@ export function installRequireHooks(
66
71
  if (
67
72
  parent &&
68
73
  parent.filename &&
69
- (RN_PATH.test(parent.filename) || isExtra(parent.filename)) &&
74
+ (NODE_MODULES.test(parent.filename) ||
75
+ RN_PATH.test(parent.filename) ||
76
+ isExtra(parent.filename)) &&
70
77
  request.startsWith(".") &&
71
78
  !path.extname(request)
72
79
  ) {
@@ -9,6 +9,14 @@ import { resolvePlatformFile } from "./resolve.mjs";
9
9
  import { buildPkgMatcher } from "./match.mjs";
10
10
 
11
11
  const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
12
+ // Any file living under a node_modules directory. Platform-extension resolution
13
+ // (`.native.js` etc.) applies to every node_modules package, not just RN, matching
14
+ // Metro — which resolves platform variants project-wide. (Without this, e.g.
15
+ // `@react-navigation/native` silently loads its `.js`/web variant instead of
16
+ // `.native.js`, breaking the navigation lifecycle with no error.)
17
+ const NODE_MODULES = /[\\/]node_modules[\\/]/;
18
+ // React Native's main entry (`react-native/index.js`).
19
+ const RN_INDEX = /[\\/]react-native[\\/]index\.js$/;
12
20
  const TRANSFORMABLE = /\.(jsx?|tsx?|mjs|cjs)$/;
13
21
  // Extensions/index candidates for bundler-style extensionless resolution.
14
22
  const RESOLVE_EXTS = [".js", ".cjs", ".mjs", ".json", ".jsx", ".ts", ".tsx"];
@@ -39,6 +47,8 @@ let REACT_NATIVE_VERSION = "0.0.0";
39
47
  let isExtra = () => false;
40
48
  // Preset package name → its mock's named-export list (from the preset definition).
41
49
  let presetExports = {};
50
+ // Asset file extensions (without leading dot, lower-cased) the loader should stub.
51
+ let assetExtSet = new Set();
42
52
 
43
53
  export async function initialize(data) {
44
54
  if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
@@ -46,6 +56,8 @@ export async function initialize(data) {
46
56
  if (data && data.reactNativeVersion) REACT_NATIVE_VERSION = data.reactNativeVersion;
47
57
  if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs);
48
58
  if (data && data.presetExports) presetExports = data.presetExports;
59
+ if (data && data.assetExts)
60
+ assetExtSet = new Set(data.assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
49
61
  }
50
62
 
51
63
  export async function resolve(specifier, context, nextResolve) {
@@ -63,7 +75,7 @@ export async function resolve(specifier, context, nextResolve) {
63
75
  : null;
64
76
  if (
65
77
  parent &&
66
- (RN_PATH.test(parent) || isExtra(parent)) &&
78
+ (NODE_MODULES.test(parent) || RN_PATH.test(parent) || isExtra(parent)) &&
67
79
  specifier.startsWith(".") &&
68
80
  !path.extname(specifier)
69
81
  ) {
@@ -71,18 +83,36 @@ export async function resolve(specifier, context, nextResolve) {
71
83
  if (hit) return { url: pathToFileURL(hit).href, shortCircuit: true };
72
84
  }
73
85
 
86
+ let resolved;
74
87
  try {
75
- return await nextResolve(specifier, context);
88
+ resolved = await nextResolve(specifier, context);
76
89
  } catch (err) {
77
90
  // Fallback: an extensionless relative import that Node's ESM resolver rejected
78
91
  // but a bundler (Metro) would accept. Common in externalized RN libs shipping
79
92
  // ESM with extensionless imports. Resolve it on disk ourselves.
80
93
  if (parent && specifier.startsWith(".") && !path.extname(specifier)) {
81
94
  const hit = resolveExtensionless(path.resolve(path.dirname(parent), specifier));
82
- if (hit) return { url: pathToFileURL(hit).href, shortCircuit: true };
95
+ if (hit) resolved = { url: pathToFileURL(hit).href, shortCircuit: true };
83
96
  }
84
- throw err;
97
+ if (!resolved) throw err;
85
98
  }
99
+
100
+ // JSON imports without an explicit `with { type: 'json' }` attribute throw
101
+ // ERR_IMPORT_ATTRIBUTE_MISSING on Node 22+. RN ecosystem packages do
102
+ // `import pkg from './package.json'` unconditionally (e.g. @react-navigation).
103
+ // Inject the attribute so Node's OWN native JSON module loader handles it —
104
+ // leaning on the platform rather than synthesizing a module source.
105
+ if (resolved.url.endsWith(".json")) {
106
+ return {
107
+ ...resolved,
108
+ importAttributes: {
109
+ ...(resolved.importAttributes ?? context.importAttributes),
110
+ type: "json",
111
+ },
112
+ shortCircuit: true,
113
+ };
114
+ }
115
+ return resolved;
86
116
  }
87
117
 
88
118
  export async function load(url, context, nextLoad) {
@@ -105,10 +135,50 @@ export async function load(url, context, nextLoad) {
105
135
  if (!url.startsWith("file:")) return nextLoad(url, context);
106
136
  const file = fileURLToPath(url);
107
137
  const norm = file.replace(/\\/g, "/");
138
+
139
+ // Asset imports (`import logo from './logo.png'`, `import font from './Icon.ttf'`)
140
+ // from ANY package: Node's ESM loader can't parse a binary asset as a module and
141
+ // throws. Stub to the basename string — matching the CJS require hook (hooks.mjs)
142
+ // and the Vite graph. Applies regardless of whether the importing package is RN
143
+ // or in `transform`, since assets are pulled in by ecosystem libs too (e.g.
144
+ // `@react-navigation/elements`' back-icon.png).
145
+ const ext = path.extname(norm).slice(1).toLowerCase();
146
+ if (ext && assetExtSet.has(ext)) {
147
+ const basename = norm.split("/").pop() || norm;
148
+ return {
149
+ format: "module",
150
+ source: `export default ${JSON.stringify(basename)};`,
151
+ shortCircuit: true,
152
+ };
153
+ }
154
+
108
155
  const isRN = RN_PATH.test(norm);
109
156
  if (!isRN && !isExtra(norm)) return nextLoad(url, context);
110
157
 
111
158
  if (isRN) {
159
+ // RN's main index exports everything via lazy getters (`module.exports = {
160
+ // get Appearance() {…}, … }`). When Node imports that CommonJS module from an
161
+ // externalized ESM lib, cjs-module-lexer can't see getter exports, so
162
+ // `import { Appearance } from 'react-native'` throws "does not provide an
163
+ // export named 'Appearance'". Serve a thin CJS re-export of the real
164
+ // (Flow-stripped) index, plus a dead `0 && (module.exports = { … })` hint that
165
+ // cjs-module-lexer DOES recognize — so Node sees the named exports while the
166
+ // real getters stay lazy (no eager load of RN's whole surface). The require()
167
+ // of react-native here goes through the separate Module._extensions hook
168
+ // (hooks.mjs), not this loader, so there's no recursion. Names come from the
169
+ // index's own `get X()` declarations.
170
+ if (RN_INDEX.test(norm)) {
171
+ const src = fs.readFileSync(file, "utf8");
172
+ const names = [
173
+ ...new Set([...src.matchAll(/\bget\s+([A-Za-z_$][\w$]*)\s*\(/g)].map((m) => m[1])),
174
+ ].filter((n) => n !== "default" && n !== "__esModule");
175
+ const facade = [
176
+ `const { createRequire } = require("node:module");`,
177
+ `module.exports = createRequire(${JSON.stringify(url)})(${JSON.stringify(file)});`,
178
+ `0 && (module.exports = { ${names.join(", ")} });`,
179
+ ].join("\n");
180
+ return { format: "commonjs", source: facade, shortCircuit: true };
181
+ }
112
182
  const boundary = boundarySourceFor(norm, PLATFORM, REACT_NATIVE_VERSION);
113
183
  if (boundary != null) return { format: "commonjs", source: boundary, shortCircuit: true };
114
184
  if (norm.endsWith(".js")) {
@@ -22,12 +22,30 @@ function extensionsFor(platform) {
22
22
  ];
23
23
  }
24
24
 
25
+ // Per-worker resolution cache: `${platform}\0${absBase}` → resolved path | null.
26
+ // Platform resolution is deterministic for a given on-disk layout, and Node's own
27
+ // module cache already dedupes most re-resolution; this dedupes the rest (distinct
28
+ // import edges resolving to the same base), so each base is scanned at most once per
29
+ // worker instead of running up to ~24 `existsSync` calls every time. Negative
30
+ // results are cached too. Lifetime is the worker process — like Vite's own
31
+ // resolution cache, a newly-added platform variant is picked up on the next restart.
32
+ const resolveCache = new Map();
33
+
25
34
  /**
26
35
  * Given an absolute base path with no extension (e.g. ".../Foo"), return the
27
36
  * first existing platform variant (".../Foo.ios.tsx", etc.) or directory index,
28
37
  * or null if none exist.
29
38
  */
30
39
  export function resolvePlatformFile(absBase, platform = "ios") {
40
+ const key = platform + "\0" + absBase;
41
+ const cached = resolveCache.get(key);
42
+ if (cached !== undefined) return cached;
43
+ const resolved = scanPlatformFile(absBase, platform);
44
+ resolveCache.set(key, resolved);
45
+ return resolved;
46
+ }
47
+
48
+ function scanPlatformFile(absBase, platform) {
31
49
  const extensions = extensionsFor(platform);
32
50
  for (const ext of extensions) {
33
51
  if (fs.existsSync(absBase + ext)) return absBase + ext;
@@ -72,6 +72,13 @@ try {
72
72
  if (process.env.VITEST_NATIVE_PRESET_NAMES)
73
73
  presetNames = JSON.parse(process.env.VITEST_NATIVE_PRESET_NAMES);
74
74
  } catch {}
75
+ // Per-preset config (preset name → JSON config), e.g. navigation route params.
76
+ // Presets are rebuilt here from their name, so any factory options come via env.
77
+ let presetConfig = {};
78
+ try {
79
+ if (process.env.VITEST_NATIVE_PRESET_CONFIG)
80
+ presetConfig = JSON.parse(process.env.VITEST_NATIVE_PRESET_CONFIG);
81
+ } catch {}
75
82
 
76
83
  // Discover preset module (package) names + their static export lists WITHOUT
77
84
  // building the mocks yet — building can lazily touch react-native, so the require
@@ -81,7 +88,7 @@ const presetExports = {}; // pkg -> string[] (named exports, for the ESM loader)
81
88
  for (const name of presetNames) {
82
89
  const factory = presetFactories[name];
83
90
  if (typeof factory !== "function") continue;
84
- const preset = factory();
91
+ const preset = factory(presetConfig[name]);
85
92
  for (const [pkg, mod] of Object.entries(preset.modules)) {
86
93
  presetDefs.push({ pkg, mod, presetName: preset.name });
87
94
  presetExports[pkg] = mod.exports || [];
@@ -106,7 +113,7 @@ if (typeof globalThis.expect === "undefined") {
106
113
  if (!globalThis.__vitest_native_loader_registered) {
107
114
  globalThis.__vitest_native_loader_registered = true;
108
115
  register("./loader.mjs", import.meta.url, {
109
- data: { projectRoot, platform, reactNativeVersion, transformPkgs, presetExports },
116
+ data: { projectRoot, platform, reactNativeVersion, transformPkgs, presetExports, assetExts },
110
117
  });
111
118
  }
112
119
  installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion, assetExts);
@@ -1,7 +1,9 @@
1
1
  // Flow-strips a React Native source file via the project's @react-native/babel-preset
2
- // (the only transformer that lowers RN's `component` syntax). Disk-cached by
3
- // path + mtime + size + preset version. Used by BOTH the loader hook (import) and
4
- // the require hook — they run in separate threads, so this module is stateless.
2
+ // (the only transformer that lowers RN's `component` syntax). Used by BOTH the loader
3
+ // hook (import) and the require hook, which run in separate threads: each gets its own
4
+ // instance of this module, so the in-memory `mem` cache below is per-thread (no shared
5
+ // mutable state to race on). The disk cache — keyed by path + mtime + size + preset
6
+ // version — is the layer shared across them.
5
7
  import { createRequire } from "node:module";
6
8
  import path from "node:path";
7
9
  import fs from "node:fs";
@@ -744,12 +744,12 @@ function createMockNavigation() {
744
744
  * useNavigation() and useRoute() inside the screen component return values
745
745
  * consistent with the route/navigation props passed to the component.
746
746
  */
747
- function createMockScreen(NavContext, RouteContext) {
747
+ function createMockScreen(NavContext, RouteContext, defaultRouteParams) {
748
748
  const Screen = React.forwardRef(({ component: Component, children, ...rest }, ref) => {
749
749
  const route = {
750
750
  key: rest.name ?? "",
751
751
  name: rest.name ?? "",
752
- params: rest.initialParams
752
+ params: rest.initialParams ?? defaultRouteParams
753
753
  };
754
754
  const nav = createMockNavigation();
755
755
  const content = Component ? React.createElement(Component, {
@@ -767,7 +767,8 @@ function createMockScreen(NavContext, RouteContext) {
767
767
  Screen.displayName = "Screen";
768
768
  return Screen;
769
769
  }
770
- function navigation() {
770
+ function navigation(presetOptions = {}) {
771
+ const defaultRouteParams = presetOptions.defaultRouteParams ?? {};
771
772
  const NavigationContext = React.createContext(null);
772
773
  const NavigationRouteContext = React.createContext(null);
773
774
  const NavigationContainerRefContext = React.createContext(null);
@@ -778,9 +779,10 @@ function navigation() {
778
779
  colors: {}
779
780
  });
780
781
  const PreventRemoveContext = React.createContext(null);
781
- const Screen = createMockScreen(NavigationContext, NavigationRouteContext);
782
+ const Screen = createMockScreen(NavigationContext, NavigationRouteContext, defaultRouteParams);
782
783
  return {
783
784
  name: "navigation",
785
+ config: { defaultRouteParams },
784
786
  modules: {
785
787
  "@react-navigation/native": {
786
788
  exports: [
@@ -867,7 +869,7 @@ function navigation() {
867
869
  const defaultRoute = {
868
870
  key: "test-route-key",
869
871
  name: "TestScreen",
870
- params: {}
872
+ params: defaultRouteParams
871
873
  };
872
874
  function useNavigation() {
873
875
  try {
@@ -746,12 +746,12 @@ function createMockNavigation() {
746
746
  * useNavigation() and useRoute() inside the screen component return values
747
747
  * consistent with the route/navigation props passed to the component.
748
748
  */
749
- function createMockScreen(NavContext, RouteContext) {
749
+ function createMockScreen(NavContext, RouteContext, defaultRouteParams) {
750
750
  const Screen = react.default.forwardRef(({ component: Component, children, ...rest }, ref) => {
751
751
  const route = {
752
752
  key: rest.name ?? "",
753
753
  name: rest.name ?? "",
754
- params: rest.initialParams
754
+ params: rest.initialParams ?? defaultRouteParams
755
755
  };
756
756
  const nav = createMockNavigation();
757
757
  const content = Component ? react.default.createElement(Component, {
@@ -769,7 +769,8 @@ function createMockScreen(NavContext, RouteContext) {
769
769
  Screen.displayName = "Screen";
770
770
  return Screen;
771
771
  }
772
- function navigation() {
772
+ function navigation(presetOptions = {}) {
773
+ const defaultRouteParams = presetOptions.defaultRouteParams ?? {};
773
774
  const NavigationContext = react.default.createContext(null);
774
775
  const NavigationRouteContext = react.default.createContext(null);
775
776
  const NavigationContainerRefContext = react.default.createContext(null);
@@ -780,9 +781,10 @@ function navigation() {
780
781
  colors: {}
781
782
  });
782
783
  const PreventRemoveContext = react.default.createContext(null);
783
- const Screen = createMockScreen(NavigationContext, NavigationRouteContext);
784
+ const Screen = createMockScreen(NavigationContext, NavigationRouteContext, defaultRouteParams);
784
785
  return {
785
786
  name: "navigation",
787
+ config: { defaultRouteParams },
786
788
  modules: {
787
789
  "@react-navigation/native": {
788
790
  exports: [
@@ -869,7 +871,7 @@ function navigation() {
869
871
  const defaultRoute = {
870
872
  key: "test-route-key",
871
873
  name: "TestScreen",
872
- params: {}
874
+ params: defaultRouteParams
873
875
  };
874
876
  function useNavigation() {
875
877
  try {
package/dist/presets.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_presets = require("./presets-BPVVlfI2.cjs");
2
+ const require_presets = require("./presets-BTG8fiNF.cjs");
3
3
  exports.asyncStorage = require_presets.asyncStorage;
4
4
  exports.deviceInfo = require_presets.deviceInfo;
5
5
  exports.expo = require_presets.expo;
@@ -1,2 +1,2 @@
1
- import { a as mmkv, c as screens, d as safeAreaContext, f as gestureHandler, i as svg, l as asyncStorage, n as vectorIcons, o as deviceInfo, p as reanimated, r as webview, s as expo, u as navigation } from "./index-Dr3WvKWI.cjs";
1
+ import { a as mmkv, c as screens, d as safeAreaContext, f as gestureHandler, i as svg, l as asyncStorage, n as vectorIcons, o as deviceInfo, p as reanimated, r as webview, s as expo, u as navigation } from "./index-BgzErxHj.cjs";
2
2
  export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
@@ -1,2 +1,2 @@
1
- import { a as mmkv, c as screens, d as safeAreaContext, f as gestureHandler, i as svg, l as asyncStorage, n as vectorIcons, o as deviceInfo, p as reanimated, r as webview, s as expo, u as navigation } from "./index-DGNLmGjq.mjs";
1
+ import { a as mmkv, c as screens, d as safeAreaContext, f as gestureHandler, i as svg, l as asyncStorage, n as vectorIcons, o as deviceInfo, p as reanimated, r as webview, s as expo, u as navigation } from "./index-DbfKy_bm.mjs";
2
2
  export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
package/dist/presets.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as mmkv, c as screens, d as safeAreaContext, f as gestureHandler, h as reanimated, i as svg, l as asyncStorage, n as vectorIcons, o as deviceInfo, r as webview, s as expo, u as navigation } from "./presets-DVLDrPC-.mjs";
1
+ import { a as mmkv, c as screens, d as safeAreaContext, f as gestureHandler, h as reanimated, i as svg, l as asyncStorage, n as vectorIcons, o as deviceInfo, r as webview, s as expo, u as navigation } from "./presets-BFuAMwYQ.mjs";
2
2
  export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
package/dist/setup.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  const require_chunk = require("./chunk-CZWwpsFl.cjs");
2
2
  const require_preset_map = require("./preset-map-CNBOeqAu.cjs");
3
- const require_presets = require("./presets-BPVVlfI2.cjs");
3
+ const require_presets = require("./presets-BTG8fiNF.cjs");
4
4
  const require_serializer = require("./serializer.cjs");
5
5
  const require_matchers = require("./matchers.cjs");
6
6
  let node_path = require("node:path");
@@ -2313,6 +2313,16 @@ function createUseAnimatedValueMock() {
2313
2313
  return new (createAnimatedMock()).Value(initialValue);
2314
2314
  });
2315
2315
  }
2316
+ function createUseAnimatedValueXYMock() {
2317
+ return vitest.vi.fn((initialValue) => {
2318
+ return new (createAnimatedMock()).ValueXY(initialValue);
2319
+ });
2320
+ }
2321
+ function createUseAnimatedColorMock() {
2322
+ return vitest.vi.fn((initialValue) => {
2323
+ return new (createAnimatedMock()).Color(initialValue);
2324
+ });
2325
+ }
2316
2326
  function buildReactNativeMock(platform = "ios") {
2317
2327
  const mock = {
2318
2328
  View: createViewMock(),
@@ -2371,6 +2381,7 @@ function buildReactNativeMock(platform = "ios") {
2371
2381
  UIManager: createUIManagerMock(),
2372
2382
  NativeEventEmitter: createNativeEventEmitterMock(),
2373
2383
  NativeAppEventEmitter: createDeviceEventEmitterMock(),
2384
+ EventEmitter: createNativeEventEmitterMock(),
2374
2385
  NativeComponentRegistry: createNativeComponentRegistryMock(),
2375
2386
  requireNativeComponent: createRequireNativeComponentMock(),
2376
2387
  AppRegistry: createAppRegistryMock(),
@@ -2383,6 +2394,8 @@ function buildReactNativeMock(platform = "ios") {
2383
2394
  Settings: createSettingsMock(),
2384
2395
  DeviceInfo: createDeviceInfoMock(),
2385
2396
  useAnimatedValue: createUseAnimatedValueMock(),
2397
+ useAnimatedValueXY: createUseAnimatedValueXYMock(),
2398
+ useAnimatedColor: createUseAnimatedColorMock(),
2386
2399
  RootTagContext: react.default.createContext(null),
2387
2400
  ReactNativeVersion: {
2388
2401
  major: 0,
package/dist/setup.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as __require } from "./chunk-CjcI7cDX.mjs";
2
2
  import { t as AUTO_DETECT_PRESETS } from "./preset-map-C1UwEald.mjs";
3
- import { m as buildPressableHostProps, p as createPressableMock, t as presets_exports } from "./presets-DVLDrPC-.mjs";
3
+ import { m as buildPressableHostProps, p as createPressableMock, t as presets_exports } from "./presets-BFuAMwYQ.mjs";
4
4
  import { serializer } from "./serializer.mjs";
5
5
  import { animatedMatchers } from "./matchers.mjs";
6
6
  import { createRequire } from "node:module";
@@ -2311,6 +2311,16 @@ function createUseAnimatedValueMock() {
2311
2311
  return new (createAnimatedMock()).Value(initialValue);
2312
2312
  });
2313
2313
  }
2314
+ function createUseAnimatedValueXYMock() {
2315
+ return vi.fn((initialValue) => {
2316
+ return new (createAnimatedMock()).ValueXY(initialValue);
2317
+ });
2318
+ }
2319
+ function createUseAnimatedColorMock() {
2320
+ return vi.fn((initialValue) => {
2321
+ return new (createAnimatedMock()).Color(initialValue);
2322
+ });
2323
+ }
2314
2324
  function buildReactNativeMock(platform = "ios") {
2315
2325
  const mock = {
2316
2326
  View: createViewMock(),
@@ -2369,6 +2379,7 @@ function buildReactNativeMock(platform = "ios") {
2369
2379
  UIManager: createUIManagerMock(),
2370
2380
  NativeEventEmitter: createNativeEventEmitterMock(),
2371
2381
  NativeAppEventEmitter: createDeviceEventEmitterMock(),
2382
+ EventEmitter: createNativeEventEmitterMock(),
2372
2383
  NativeComponentRegistry: createNativeComponentRegistryMock(),
2373
2384
  requireNativeComponent: createRequireNativeComponentMock(),
2374
2385
  AppRegistry: createAppRegistryMock(),
@@ -2381,6 +2392,8 @@ function buildReactNativeMock(platform = "ios") {
2381
2392
  Settings: createSettingsMock(),
2382
2393
  DeviceInfo: createDeviceInfoMock(),
2383
2394
  useAnimatedValue: createUseAnimatedValueMock(),
2395
+ useAnimatedValueXY: createUseAnimatedValueXYMock(),
2396
+ useAnimatedColor: createUseAnimatedColorMock(),
2384
2397
  RootTagContext: React.createContext(null),
2385
2398
  ReactNativeVersion: {
2386
2399
  major: 0,
@@ -114,7 +114,9 @@ no-op under the shim (use `test.testTimeout` in config or per-test `{ timeout }`
114
114
  2. Delete manual third-party native-lib mocks and `@react-native/jest-preset` (2c, 2e).
115
115
  3. Convert any **top-level** `jest.mock(...)` to `vi.mock(...)`; leave runtime `jest.*` as-is (2a).
116
116
  4. Run `vitest run -u` once to re-record snapshots (2d), then `vitest run` to confirm green.
117
- 5. Triage remaining failures — usually a missing query update or a suite-specific mock.
117
+ 5. Triage remaining failures — usually a missing query update or a suite-specific mock. For runtime
118
+ issues (large-suite memory limits, error-boundary console noise, overriding a preset's mock), see
119
+ the [Troubleshooting](../README.md#troubleshooting) section.
118
120
 
119
121
  ## 4. What "done" looks like
120
122
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitest-native",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Run real React Native tests under Vitest. One install, zero config.",
6
6
  "license": "MIT",
@@ -161,6 +161,8 @@
161
161
  "@vitest/coverage-v8": "4.1.8",
162
162
  "expo-constants": "56.0.16",
163
163
  "expo-status-bar": "56.0.4",
164
+ "ext-platform-lib": "file:./tests-native/fixtures/ext-platform-lib",
165
+ "ext-rn-named-lib": "file:./tests-native/fixtures/ext-rn-named-lib",
164
166
  "react": "^19.2.3",
165
167
  "react-native": "^0.85.3",
166
168
  "react-native-gesture-handler": "3.0.0",
@@ -177,6 +179,7 @@
177
179
  "build": "tsdown",
178
180
  "test": "vitest run",
179
181
  "test:native": "vitest run --config tests-native/vitest.config.mts",
182
+ "test:native:navigation": "vitest run --config tests-native/vitest.navigation.config.mts",
180
183
  "test:native:android": "vitest run --config tests-native/vitest.android.config.mts",
181
184
  "test:native:hot": "vitest run --config tests-native/vitest.hot.config.mts",
182
185
  "test:native:hot:isolation": "vitest run --config tests-native/vitest.hot-isolation.config.mts",
@@ -188,7 +191,7 @@
188
191
  "check-compat": "bun scripts/check-compat.ts",
189
192
  "typecheck": "tsc --noEmit",
190
193
  "clean": "rm -rf dist",
191
- "prepublishOnly": "bun run build && bun run test && bun run test:native && bun run test:native:android && bun run test:native:hot && bun run test:native:hot:isolation && bun run test:native:hot:soak && bun run crosscheck && bun run test:consumers && bun run lint && bun run typecheck",
194
+ "prepublishOnly": "bun run build && bun run test && bun run test:native && bun run test:native:navigation && bun run test:native:android && bun run test:native:hot && bun run test:native:hot:isolation && bun run test:native:hot:soak && bun run crosscheck && bun run test:consumers && bun run lint && bun run typecheck",
192
195
  "crosscheck": "node scripts/crosscheck.mjs"
193
196
  },
194
197
  "dependencies": {