vitest-native 0.6.1 → 0.8.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,89 @@
1
1
  # vitest-native
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 067e2aa: Add built-in presets for `@shopify/flash-list`, `@gorhom/bottom-sheet`, and `react-native-keyboard-controller`.
8
+
9
+ These libraries rely on native runtimes (a native recycler, reanimated worklets, and keyboard native modules) that cannot run under Node, so before this they had to be mocked by hand. Each is now auto-detected when installed and shadowed by a self-contained preset under both engines: `FlashList` renders its data through `renderItem` so rows stay queryable, the bottom-sheet containers render their children through real React Native with no-op imperative refs, and the keyboard-controller containers render their children while `KeyboardController` and the reanimated-backed hooks return inert handles.
10
+
11
+ - b31e3d9: Support `@testing-library/react-native` 14 alongside 12 and 13.
12
+
13
+ RNTL 14 made `render`, `fireEvent`, and `act` asynchronous and reconciles with the new
14
+ `test-renderer` (replacing `react-test-renderer`). Two changes make the native engine work
15
+ across the full supported peer range (`>=12 <15`) from a single setup:
16
+
17
+ - Register `RCTVirtualText` as a text host under the native engine. Real React Native renders a
18
+ nested `<Text>` as the host `RCTVirtualText`, which RNTL 14's `test-renderer` did not recognize
19
+ as text — so any composite or nested `<Text>` threw "Text strings must be rendered within a
20
+ `<Text>` component". Nested and composite text now render and match correctly.
21
+ - The engine itself is RNTL-version agnostic; the only caller-visible difference is that RNTL 14's
22
+ `render`/`fireEvent`/`act` must be awaited. Awaiting them is back-compatible with RNTL 12/13,
23
+ where the calls are synchronous.
24
+
25
+ CI now exercises RNTL 12, 13, and 14. Note that RNTL 14 requires Node >= 22.13; on Node 20, use
26
+ RNTL 13.
27
+
28
+ ### Patch Changes
29
+
30
+ - 489a536: Scope React Native path detection to `node_modules`. The native engine identified
31
+ React Native package files with the regex `/[\\/]react-native[\\/]/`, which also
32
+ matched any project checked out under a directory named `react-native` (for example
33
+ `/home/runner/work/react-native/react-native/` in CI for a repo named `react-native`).
34
+ Every project file then matched, so `.tsx` test files were externalized and sent raw
35
+ to Node (`Unknown file extension ".tsx"`) and `vi.mock()` calls stopped hoisting.
36
+ The matchers in `apply.ts`, `loader.mjs`, and `hooks.mjs` now require a
37
+ `node_modules/` segment, which still matches real RN and `@react-native/*` packages
38
+ (including pnpm-nested layouts) without false-matching project paths. Reported and fixed
39
+ by [@Doko-Demo-Doa](https://github.com/Doko-Demo-Doa) (#50).
40
+ - 5eaf8cb: Cache the React Native graph's compiled bytecode under the native engine.
41
+
42
+ With per-file isolation (`engine: 'native'`, the default), React Native's module graph is re-instantiated for every test file, recompiling its source to V8 bytecode each time. The native engine now enables Node's on-disk compile cache (Node 22.8+) before React Native is loaded, so subsequent compilations across files, workers, and runs reuse cached bytecode. Measured on a 100-file suite (single worker), this reduced cold time by ~7% and warm time by ~7-18% with tighter run-to-run variance and no change in memory use. It is a no-op on Node versions without the compile-cache API.
43
+
44
+ ## 0.7.0
45
+
46
+ ### Minor Changes
47
+
48
+ - 37c8123: Native engine: Metro-style resolution for externalized node_modules packages, plus navigation route params and jest-compat timer leniency
49
+
50
+ Vitest externalizes most `node_modules` dependencies (any that Node can import
51
+ natively), so they load through Node rather than Vite — and Node's resolver has no
52
+ notion of React Native's Metro conventions. The native engine now fills those gaps
53
+ for externalized packages:
54
+
55
+ - **Platform extensions** — `import './x'` resolves `x.native.js` / `x.ios.js` /
56
+ `x.android.js` over the default `x.js`, for any `node_modules` package (matching
57
+ Metro and Vite's behavior for inlined code). Previously only `react-native` and
58
+ packages in `transform` got this, so e.g. `@react-navigation` silently loaded its
59
+ web variant (`useLinking.js`), breaking the navigation lifecycle with no error.
60
+ - **Asset imports** — `import icon from './icon.png'` (and other asset extensions)
61
+ resolve to the basename string instead of throwing "Unknown file extension" in
62
+ Node's ESM loader.
63
+ - **JSON imports** — `import data from './data.json'` without a `with { type: 'json' }`
64
+ attribute no longer throws `ERR_IMPORT_ATTRIBUTE_MISSING` on Node 22+. The native
65
+ engine injects the attribute so Node's own JSON module loader handles it.
66
+
67
+ Other changes:
68
+
69
+ - **`navigation` preset** accepts `defaultRouteParams`, used by the mocked
70
+ `useRoute().params` (and as a `<Screen>`'s fallback params) — so components that
71
+ read route params at mount can be tested without a custom `vi.mock`.
72
+ - **jest-compat** `jest.advanceTimersByTime` / `advanceTimersByTimeAsync` are now
73
+ no-ops when fake timers are inactive, matching Jest's lenient behavior (Vitest's
74
+ `vi` throws). This fixes RNTL `userEvent.setup({ advanceTimers })` on suites that
75
+ never enable fake timers. All other `jest` methods continue to forward to `vi`.
76
+
77
+ ### Patch Changes
78
+
79
+ - 5a86872: Add mocks for react-native 0.86 top-level exports
80
+
81
+ The weekly compatibility check flagged new stable exports in react-native 0.86.
82
+ `EventEmitter`, `useAnimatedColor`, and `useAnimatedValueXY` are now mocked so
83
+ named imports resolve under the mock engine. The experimental virtualized-collection
84
+ API (`unstable_VirtualRow`, `unstable_createVirtualCollectionView`, and related)
85
+ is added to the compatibility check's known-skipped list.
86
+
3
87
  ## 0.6.1
4
88
 
5
89
  ### Patch Changes
package/README.md CHANGED
@@ -451,19 +451,23 @@ export default defineConfig({
451
451
 
452
452
  ### Available Presets
453
453
 
454
- | Import | Function |
455
- | --------------------------- | ----------------------------------------- |
456
- | `presets.reanimated()` | react-native-reanimated |
457
- | `presets.gestureHandler()` | react-native-gesture-handler |
458
- | `presets.safeAreaContext()` | react-native-safe-area-context |
459
- | `presets.navigation()` | @react-navigation/native |
460
- | `presets.asyncStorage()` | @react-native-async-storage/async-storage |
461
- | `presets.screens()` | react-native-screens |
462
- | `presets.expo()` | Expo modules |
463
- | `presets.deviceInfo()` | react-native-device-info |
464
- | `presets.mmkv()` | react-native-mmkv |
465
- | `presets.svg()` | react-native-svg |
466
- | `presets.webview()` | react-native-webview |
454
+ | Import | Function |
455
+ | ------------------------------ | ----------------------------------------- |
456
+ | `presets.reanimated()` | react-native-reanimated |
457
+ | `presets.gestureHandler()` | react-native-gesture-handler |
458
+ | `presets.safeAreaContext()` | react-native-safe-area-context |
459
+ | `presets.navigation()` | @react-navigation/native |
460
+ | `presets.asyncStorage()` | @react-native-async-storage/async-storage |
461
+ | `presets.screens()` | react-native-screens |
462
+ | `presets.expo()` | Expo modules |
463
+ | `presets.deviceInfo()` | react-native-device-info |
464
+ | `presets.mmkv()` | react-native-mmkv |
465
+ | `presets.svg()` | react-native-svg |
466
+ | `presets.webview()` | react-native-webview |
467
+ | `presets.vectorIcons()` | react-native-vector-icons |
468
+ | `presets.flashList()` | @shopify/flash-list |
469
+ | `presets.bottomSheet()` | @gorhom/bottom-sheet |
470
+ | `presets.keyboardController()` | react-native-keyboard-controller |
467
471
 
468
472
  Presets apply under **both** engines: the mock engine and `engine: 'native'` (where they shadow each
469
473
  library's native runtime — worklets, native modules — exactly as Jest does, while the surrounding tree
@@ -573,6 +577,41 @@ preset.
573
577
  Real RN computes host props (e.g. `<Text>`'s `accessible`, `allowFontScaling`) that mocks omit, so
574
578
  the tree is richer. Re-record once with `npx vitest -u` after migrating.
575
579
 
580
+ **`Worker terminated due to reaching memory limit` / `JS heap out of memory` (large native suites)**
581
+ Every test file that renders real React Native loads a full renderer, so a large suite can grow a
582
+ worker's heap past Node's default ceiling. Cap it with Vitest's per-worker limit — Vitest recycles a
583
+ worker once its heap exceeds the limit, so growth never reaches the hard OOM:
584
+
585
+ ```ts
586
+ // vitest.config.ts
587
+ export default defineConfig({
588
+ test: { poolOptions: { threads: { memoryLimit: "512MB" } } },
589
+ });
590
+ ```
591
+
592
+ The experimental `reactNative({ hotRuntime: true })` also helps: it keeps React Native resident
593
+ across files (loaded once per worker instead of per file) and recycles workers on a memory/file
594
+ budget.
595
+
596
+ **`Vitest caught N unhandled errors` in error-boundary tests**
597
+ A test that intentionally throws inside a component (to exercise an error boundary) makes React log
598
+ a "recovered from an error during concurrent rendering" message and Vitest count it — even though
599
+ the boundary worked and the test passes. It's cosmetic and the assertions are unaffected. Silence it
600
+ in a setup file if you like (e.g. filter the message in an `onConsoleLog`/`console.error` wrapper).
601
+
602
+ **Overriding a preset's mock (e.g. navigation route params)**
603
+ Auto-detected presets shadow a library with a built-in mock. To change what that mock returns for a
604
+ test or project, `vi.mock` the module in a setup file and spread the preset's mock — presets expose
605
+ the module to Vitest's graph, so `vi.mock` applies and `importOriginal()` returns the preset mock:
606
+
607
+ ```ts
608
+ // vitest.setup.ts
609
+ vi.mock("@react-navigation/native", async (importOriginal) => ({
610
+ ...(await importOriginal()),
611
+ useRoute: () => ({ key: "r", name: "Screen", params: { id: "1" } }),
612
+ }));
613
+ ```
614
+
576
615
  ---
577
616
 
578
617
  ## RNTL Matchers
@@ -739,6 +778,14 @@ export default defineConfig({
739
778
  });
740
779
  ```
741
780
 
781
+ Platform resolution applies both to your app/test code (resolved by Vite) **and** to
782
+ third-party `node_modules` packages with platform-specific files (e.g.
783
+ `@react-navigation`'s `useLinking.native.js`). The latter matters because Vitest
784
+ externalizes most `node_modules` dependencies — they load through Node, whose resolver
785
+ has no notion of `.native.js`. The native engine fills that gap so externalized packages
786
+ resolve the same `.native`/`.ios`/`.android` variant Metro would, instead of silently
787
+ falling back to the default (often web) file.
788
+
742
789
  ---
743
790
 
744
791
  ## Asset Stubs
@@ -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 {
@@ -160,6 +162,7 @@ interface ReactNativeMock {
160
162
  UIManager: Record<string, any>;
161
163
  NativeEventEmitter: new (...args: any[]) => any;
162
164
  NativeAppEventEmitter: Record<string, any>;
165
+ EventEmitter: new (...args: any[]) => any;
163
166
  NativeComponentRegistry: Record<string, any>;
164
167
  requireNativeComponent: Mock;
165
168
  AppRegistry: Record<string, Mock>;
@@ -172,6 +175,8 @@ interface ReactNativeMock {
172
175
  Settings: Record<string, Mock>;
173
176
  DeviceInfo: Record<string, any>;
174
177
  useAnimatedValue: Mock;
178
+ useAnimatedValueXY: Mock;
179
+ useAnimatedColor: Mock;
175
180
  RootTagContext: React.Context<any>;
176
181
  ReactNativeVersion: {
177
182
  major: number;
@@ -201,6 +206,29 @@ interface PresetModule {
201
206
  interface Preset {
202
207
  name: string;
203
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>;
204
232
  }
205
233
  interface VitestNativeOptions {
206
234
  /** Target platform. Default: 'ios' */
@@ -299,7 +327,7 @@ declare function gestureHandler(): Preset;
299
327
  declare function safeAreaContext(): Preset;
300
328
  //#endregion
301
329
  //#region src/presets/navigation.d.ts
302
- declare function navigation(): Preset;
330
+ declare function navigation(presetOptions?: NavigationPresetOptions): Preset;
303
331
  //#endregion
304
332
  //#region src/presets/async-storage.d.ts
305
333
  declare function asyncStorage(): Preset;
@@ -324,8 +352,17 @@ declare function webview(): Preset;
324
352
  //#endregion
325
353
  //#region src/presets/vector-icons.d.ts
326
354
  declare function vectorIcons(): Preset;
355
+ //#endregion
356
+ //#region src/presets/flash-list.d.ts
357
+ declare function flashList(): Preset;
358
+ //#endregion
359
+ //#region src/presets/bottom-sheet.d.ts
360
+ declare function bottomSheet(): Preset;
361
+ //#endregion
362
+ //#region src/presets/keyboard-controller.d.ts
363
+ declare function keyboardController(): Preset;
327
364
  declare namespace index_d_exports {
328
- export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
365
+ export { asyncStorage, bottomSheet, deviceInfo, expo, flashList, gestureHandler, keyboardController, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
329
366
  }
330
367
  //#endregion
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 };
368
+ export { Preset as _, vectorIcons as a, mmkv as c, screens as d, asyncStorage as f, reanimated as g, gestureHandler as h, flashList as i, deviceInfo as l, safeAreaContext as m, keyboardController as n, webview as o, navigation as p, bottomSheet as r, svg as s, index_d_exports as t, expo as u, ReactNativeMock as v, VitestNativeOptions as y };
@@ -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 {
@@ -162,6 +160,7 @@ interface ReactNativeMock {
162
160
  UIManager: Record<string, any>;
163
161
  NativeEventEmitter: new (...args: any[]) => any;
164
162
  NativeAppEventEmitter: Record<string, any>;
163
+ EventEmitter: new (...args: any[]) => any;
165
164
  NativeComponentRegistry: Record<string, any>;
166
165
  requireNativeComponent: Mock;
167
166
  AppRegistry: Record<string, Mock>;
@@ -174,6 +173,8 @@ interface ReactNativeMock {
174
173
  Settings: Record<string, Mock>;
175
174
  DeviceInfo: Record<string, any>;
176
175
  useAnimatedValue: Mock;
176
+ useAnimatedValueXY: Mock;
177
+ useAnimatedColor: Mock;
177
178
  RootTagContext: React.Context<any>;
178
179
  ReactNativeVersion: {
179
180
  major: number;
@@ -203,6 +204,29 @@ interface PresetModule {
203
204
  interface Preset {
204
205
  name: string;
205
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>;
206
230
  }
207
231
  interface VitestNativeOptions {
208
232
  /** Target platform. Default: 'ios' */
@@ -301,7 +325,7 @@ declare function gestureHandler(): Preset;
301
325
  declare function safeAreaContext(): Preset;
302
326
  //#endregion
303
327
  //#region src/presets/navigation.d.ts
304
- declare function navigation(): Preset;
328
+ declare function navigation(presetOptions?: NavigationPresetOptions): Preset;
305
329
  //#endregion
306
330
  //#region src/presets/async-storage.d.ts
307
331
  declare function asyncStorage(): Preset;
@@ -326,8 +350,17 @@ declare function webview(): Preset;
326
350
  //#endregion
327
351
  //#region src/presets/vector-icons.d.ts
328
352
  declare function vectorIcons(): Preset;
353
+ //#endregion
354
+ //#region src/presets/flash-list.d.ts
355
+ declare function flashList(): Preset;
356
+ //#endregion
357
+ //#region src/presets/bottom-sheet.d.ts
358
+ declare function bottomSheet(): Preset;
359
+ //#endregion
360
+ //#region src/presets/keyboard-controller.d.ts
361
+ declare function keyboardController(): Preset;
329
362
  declare namespace index_d_exports {
330
- export { asyncStorage, deviceInfo, expo, gestureHandler, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
363
+ export { asyncStorage, bottomSheet, deviceInfo, expo, flashList, gestureHandler, keyboardController, mmkv, navigation, reanimated, safeAreaContext, screens, svg, vectorIcons, webview };
331
364
  }
332
365
  //#endregion
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 };
366
+ export { Preset as _, vectorIcons as a, mmkv as c, screens as d, asyncStorage as f, reanimated as g, gestureHandler as h, flashList as i, deviceInfo as l, safeAreaContext as m, keyboardController as n, webview as o, navigation as p, bottomSheet as r, svg as s, index_d_exports as t, expo as u, ReactNativeMock as v, VitestNativeOptions as y };
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
- const require_preset_map = require("./preset-map-CNBOeqAu.cjs");
4
- const require_presets = require("./presets-BPVVlfI2.cjs");
3
+ const require_preset_map = require("./preset-map-BY9zk9Pj.cjs");
4
+ const require_presets = require("./presets-7eMfp7o2.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);
@@ -167,8 +167,8 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
167
167
  runner: hot.runnerPath
168
168
  } : { pool: "threads" },
169
169
  server: { deps: { external: [
170
- /[\\/]react-native[\\/]/,
171
- /[\\/]@react-native[\\/]/,
170
+ /[\\/]node_modules[\\/]react-native[\\/]/,
171
+ /[\\/]node_modules[\\/]@react-native[\\/]/,
172
172
  ...extraExternal
173
173
  ] } }
174
174
  }
@@ -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 { _ as Preset, t as index_d_exports, v as ReactNativeMock, y as VitestNativeOptions } from "./index-YjjYELG7.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 { _ as Preset, t as index_d_exports, v as ReactNativeMock, y as VitestNativeOptions } from "./index-vlK4zxuK.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
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-C1UwEald.mjs";
2
- import { t as presets_exports } from "./presets-DVLDrPC-.mjs";
1
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-DCWaM08s.mjs";
2
+ import { t as presets_exports } from "./presets-23FJ76O4.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import path from "node:path";
@@ -162,8 +162,8 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
162
162
  runner: hot.runnerPath
163
163
  } : { pool: "threads" },
164
164
  server: { deps: { external: [
165
- /[\\/]react-native[\\/]/,
166
- /[\\/]@react-native[\\/]/,
165
+ /[\\/]node_modules[\\/]react-native[\\/]/,
166
+ /[\\/]node_modules[\\/]@react-native[\\/]/,
167
167
  ...extraExternal
168
168
  ] } }
169
169
  }
@@ -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
@@ -0,0 +1,40 @@
1
+ // V8 compile-cache for the externalized React Native graph.
2
+ //
3
+ // RN is loaded through Node (externalized), and our require/loader hooks compile
4
+ // each RN module's Flow-stripped source with `mod._compile` / a synthetic module
5
+ // source. The transform disk cache (transform.mjs) means Babel runs once per RN
6
+ // version — but V8 still re-parses and re-compiles that source to bytecode on
7
+ // every fresh module graph. Under `engine:'native'` (isolate:true) RN's ~240-file
8
+ // graph is re-instantiated per test FILE, so that V8 compile is paid over and
9
+ // over. Node's on-disk compile cache (Node 22.8+) keys bytecode by source content
10
+ // + Node version and is shared process-wide, so the second compile of any RN
11
+ // module — the next file, the next worker, the next run — loads bytecode instead
12
+ // of recompiling. Verified to apply to `mod._compile`, which is how the hooks load
13
+ // RN. No-op on Node < 22.8 (the API is absent) and harmless when caching is off.
14
+ import nodeModule from "node:module";
15
+ import os from "node:os";
16
+ import path from "node:path";
17
+
18
+ let _enabled = false;
19
+
20
+ /**
21
+ * Enable Node's persistent V8 compile cache for this worker/thread. Idempotent and
22
+ * guarded per realm. Colocated under the `vitest-native-cache` tmp prefix so it
23
+ * shares the transform cache's lifecycle (cleared with it on a cold run, reused on
24
+ * warm). Must be called before RN's modules are first compiled.
25
+ */
26
+ export function enableV8CompileCache() {
27
+ if (_enabled) return;
28
+ _enabled = true;
29
+ const enable = nodeModule.enableCompileCache;
30
+ if (typeof enable !== "function") return; // Node < 22.8: feature absent
31
+ try {
32
+ enable.call(nodeModule, path.join(os.tmpdir(), "vitest-native-cache-v8"));
33
+ // No atomic-write handling needed (unlike the transform cache, which writes
34
+ // executable source): Node CRC32-validates each compile-cache entry on read,
35
+ // so a torn or raced write from concurrent workers is a cache miss and a
36
+ // recompile, never a corruption-induced failure.
37
+ } catch {
38
+ // Read-only tmp, unsupported platform, etc. — caching is a pure optimization.
39
+ }
40
+ }
@@ -8,7 +8,12 @@ import { boundarySourceFor } from "./boundary.mjs";
8
8
  import { resolvePlatformFile } from "./resolve.mjs";
9
9
  import { buildPkgMatcher } from "./match.mjs";
10
10
 
11
- const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
11
+ const RN_PATH = /[\\/]node_modules[\\/](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
  ) {
@@ -8,7 +8,13 @@ import { boundarySourceFor } from "./boundary.mjs";
8
8
  import { resolvePlatformFile } from "./resolve.mjs";
9
9
  import { buildPkgMatcher } from "./match.mjs";
10
10
 
11
- const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
11
+ const RN_PATH = /[\\/]node_modules[\\/](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[\\/]/;
12
18
  // React Native's main entry (`react-native/index.js`).
13
19
  const RN_INDEX = /[\\/]react-native[\\/]index\.js$/;
14
20
  const TRANSFORMABLE = /\.(jsx?|tsx?|mjs|cjs)$/;
@@ -41,6 +47,8 @@ let REACT_NATIVE_VERSION = "0.0.0";
41
47
  let isExtra = () => false;
42
48
  // Preset package name → its mock's named-export list (from the preset definition).
43
49
  let presetExports = {};
50
+ // Asset file extensions (without leading dot, lower-cased) the loader should stub.
51
+ let assetExtSet = new Set();
44
52
 
45
53
  export async function initialize(data) {
46
54
  if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
@@ -48,6 +56,8 @@ export async function initialize(data) {
48
56
  if (data && data.reactNativeVersion) REACT_NATIVE_VERSION = data.reactNativeVersion;
49
57
  if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs);
50
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()));
51
61
  }
52
62
 
53
63
  export async function resolve(specifier, context, nextResolve) {
@@ -65,7 +75,7 @@ export async function resolve(specifier, context, nextResolve) {
65
75
  : null;
66
76
  if (
67
77
  parent &&
68
- (RN_PATH.test(parent) || isExtra(parent)) &&
78
+ (NODE_MODULES.test(parent) || RN_PATH.test(parent) || isExtra(parent)) &&
69
79
  specifier.startsWith(".") &&
70
80
  !path.extname(specifier)
71
81
  ) {
@@ -73,18 +83,36 @@ export async function resolve(specifier, context, nextResolve) {
73
83
  if (hit) return { url: pathToFileURL(hit).href, shortCircuit: true };
74
84
  }
75
85
 
86
+ let resolved;
76
87
  try {
77
- return await nextResolve(specifier, context);
88
+ resolved = await nextResolve(specifier, context);
78
89
  } catch (err) {
79
90
  // Fallback: an extensionless relative import that Node's ESM resolver rejected
80
91
  // but a bundler (Metro) would accept. Common in externalized RN libs shipping
81
92
  // ESM with extensionless imports. Resolve it on disk ourselves.
82
93
  if (parent && specifier.startsWith(".") && !path.extname(specifier)) {
83
94
  const hit = resolveExtensionless(path.resolve(path.dirname(parent), specifier));
84
- if (hit) return { url: pathToFileURL(hit).href, shortCircuit: true };
95
+ if (hit) resolved = { url: pathToFileURL(hit).href, shortCircuit: true };
85
96
  }
86
- throw err;
97
+ if (!resolved) throw err;
87
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;
88
116
  }
89
117
 
90
118
  export async function load(url, context, nextLoad) {
@@ -107,6 +135,23 @@ export async function load(url, context, nextLoad) {
107
135
  if (!url.startsWith("file:")) return nextLoad(url, context);
108
136
  const file = fileURLToPath(url);
109
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
+
110
155
  const isRN = RN_PATH.test(norm);
111
156
  if (!isRN && !isExtra(norm)) return nextLoad(url, context);
112
157