vitest-native 0.8.0 → 0.9.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 (46) hide show
  1. package/CHANGELOG.md +332 -0
  2. package/README.md +15 -1
  3. package/dist/cli.cjs +506 -0
  4. package/dist/cli.d.cts +4 -0
  5. package/dist/cli.d.mts +4 -0
  6. package/dist/cli.mjs +502 -0
  7. package/dist/ecosystem-BIWaVwYL.cjs +294 -0
  8. package/dist/ecosystem-EFtHnKS9.mjs +256 -0
  9. package/dist/{index-vlK4zxuK.d.mts → index-CEgRDdhd.d.cts} +13 -3
  10. package/dist/{index-YjjYELG7.d.cts → index-j-0tueBr.d.mts} +11 -5
  11. package/dist/index.cjs +345 -200
  12. package/dist/index.d.cts +1 -1
  13. package/dist/index.d.mts +1 -1
  14. package/dist/index.mjs +341 -196
  15. package/dist/jest-compat/setup.mjs +65 -1
  16. package/dist/native/boundary.mjs +108 -30
  17. package/dist/native/compile-cache.mjs +10 -5
  18. package/dist/native/explain.mjs +69 -0
  19. package/dist/native/hooks.mjs +76 -3
  20. package/dist/native/loader.mjs +35 -6
  21. package/dist/native/match.mjs +107 -8
  22. package/dist/native/registry.mjs +471 -0
  23. package/dist/native/reset.mjs +18 -12
  24. package/dist/native/runner.mjs +13 -7
  25. package/dist/native/setup.mjs +15 -1
  26. package/dist/native/transform.mjs +88 -19
  27. package/dist/native/worker.mjs +10 -1
  28. package/dist/pool-CJmjRgsB.mjs +117 -0
  29. package/dist/pool-DzsEo9vv.cjs +121 -0
  30. package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-CG4FMtsl.cjs} +1 -0
  31. package/dist/{preset-map-DCWaM08s.mjs → preset-map-CNsZKfvu.mjs} +1 -0
  32. package/dist/{presets-7eMfp7o2.cjs → presets-C4faM3ds.cjs} +133 -2
  33. package/dist/{presets-23FJ76O4.mjs → presets-CuDrNA_W.mjs} +128 -3
  34. package/dist/presets.cjs +2 -1
  35. package/dist/presets.d.cts +2 -2
  36. package/dist/presets.d.mts +2 -2
  37. package/dist/presets.mjs +2 -2
  38. package/dist/setup.cjs +318 -130
  39. package/dist/setup.mjs +318 -130
  40. package/docs/hot-default-design.md +129 -0
  41. package/docs/migrating-from-jest.md +43 -7
  42. package/docs/migrating-from-vitest-react-native.md +1 -1
  43. package/docs/release-readiness.md +2 -1
  44. package/package.json +17 -5
  45. package/dist/pool-B7LBfcMQ.mjs +0 -67
  46. package/dist/pool-p54QV1dQ.cjs +0 -69
package/CHANGELOG.md CHANGED
@@ -1,5 +1,337 @@
1
1
  # vitest-native
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3b08c19: Actionable errors and engine transparency for migration failure points.
8
+
9
+ - **Untransformed-package explainer**: when an externalized `node_modules` file throws a SyntaxError that fingerprints as untranspiled JSX/Flow/TypeScript (`Unexpected token '<'` and friends), the error now names the owning package and states the fix — `reactNative({ transform: ['<pkg>'] })` — with a link to the migration guide, instead of a bare Node compile stack. This is the single most common migration blocker observed in real-app bake-offs.
10
+ - **Decorated Babel failures**: a Babel crash inside the native transform now reports the file, platform, and owning package at the single transform choke point (ESM loader, CJS require hook, and `requireActual` all inherit it), chaining the original error as `cause`.
11
+ - **Engine banner**: one log line per process states which engine actually ran (`engine: native — real react-native@X` / `engine: mock — …`), so a silent `auto` fallback can never masquerade as real-RN testing.
12
+ - **Config-time fail-fast**: explicit `engine: 'native'` without `@react-native/babel-preset` / `@babel/core` now fails at config time with install instructions, instead of starting the run and dying inside the loader. The `auto`→mock fallback notice is now emitted via `console.warn`, and the Flow-strip parse-failure warning is always visible (no longer diagnostics-gated).
13
+ - **jest-compat signposts**: `jest.isolateModules`, `jest.createMockFromModule`, `jest.genMockFromModule`, and `jest.deepUnmock` now throw errors that name the API and its closest Vitest migration instead of bare `is not a function` TypeErrors; `jest.retryTimes` warns once and continues instead of crashing the suite.
14
+
15
+ - a6a6ae3: The mock engine's Animated is now a live node graph, matching real React Native's semantics (previously it was a snapshot system — the largest known fidelity gap, and the class real-app bake-offs had to monkeypatch around).
16
+
17
+ - **Derived nodes are live.** `interpolate()` (numeric AND string), `add`/`subtract`/`multiply`/`divide`/`modulo`, and `diffClamp` recompute from their sources on every read and re-notify listeners when any source moves. Numeric interpolations chain; derived nodes are valid operands (previously coerced to 0); chaining off a string interpolation still throws like RN.
18
+ - **Animated components re-render.** `Animated.View`/`Text`/`Image`/`ScrollView`/`FlatList`/`SectionList` and `createAnimatedComponent` wrappers subscribe to every node in their style — a `setValue()` or `timing().start()` after render updates the rendered style, so `toHaveStyle` assertions see current values. Gated against real React Native by three new crosscheck probes (post-render `setValue`, live interpolation, live transform) — the corpus is now 78/78.
19
+ - **Offsets are real.** `setOffset`/`flattenOffset`/`extractOffset` implement RN's semantics (the canonical PanResponder drag pattern) on `Value` and `ValueXY`; `ValueXY.addListener` now reports the joint `{x, y}` value.
20
+ - **`__getValue()` exists on plain values** (RN's own tests call it), and `AnimatedValueXY`/`AnimatedColor` gained `__getValue`/`getValue` parity.
21
+ - **`useAnimatedValue`/`useAnimatedValueXY`/`useAnimatedColor` are real hooks**: the value is `useRef`-memoized and survives re-renders (previously every render minted a fresh node, silently resetting animation state — and rebuilt the entire Animated namespace to do it). Consequently they must now be called inside a component, exactly like on-device.
22
+
23
+ - ac70dec: Compile React Native packages from `node_modules` automatically
24
+
25
+ Most of the React Native ecosystem publishes untranspiled source — JSX, Flow, or
26
+ TypeScript — assuming Metro will compile it. Node cannot run that, so every project
27
+ had to discover its own allowlist one `SyntaxError: Unexpected token '<'` at a time
28
+ and maintain it by hand in `transform: [...]`.
29
+
30
+ `engine: 'native'` now detects those packages: any dependency declaring `react-native`
31
+ in **its own** manifest is compiled with the project's React Native Babel preset and
32
+ inlined into the test graph. The manifest is the authority rather than a name pattern —
33
+ `react-native-*` misses `@gorhom/bottom-sheet` and would wrongly claim `react-native`
34
+ itself.
35
+
36
+ Because those packages land in the graph Vitest owns rather than being externalized,
37
+ `vi.mock('the-package')` now reaches them too. Mocking `react-native` itself still does
38
+ not change what a library sees — its own imports compile to `require`, which reaches
39
+ React Native directly.
40
+
41
+ Dependencies are read from the project's manifest and every manifest above it, so a
42
+ workspace that declares its React Native libraries at the repository root is covered.
43
+
44
+ Excluded automatically: packages a preset already shadows (their real source never
45
+ loads) and the test infrastructure — `@testing-library/react-native` and the renderers,
46
+ where a second copy in the graph corrupts rendering. `transform: [...]` keeps its
47
+ existing meaning for anything detection misses, and takes precedence over it.
48
+
49
+ - bbbfc5d: Stub Expo's dev-server messageSocket under the native engine.
50
+
51
+ `expo`'s `Expo.fx` requires `async-require/messageSocket` whenever `__DEV__ && globalThis.expo`, and that module throws at load time when the bundle wasn't served over HTTP ("Cannot create devtools websocket connections in embedded environments"). Under the native engine this took down any suite importing an `expo-*` package (e.g. `expo-image`) — the primary blocker for Expo apps. The module's only job is a devtools websocket to a live dev server, an environment that doesn't exist under Node, so it is now stubbed to a no-op via the boundary mechanism — matching Jest's dev-server-layer mocks. All published variants are covered (`build/` output and `src/` TS sources, plain and `.native`), and the `.ts`/`.tsx` require handlers now consult boundary stubs, which previously only `.js` did.
52
+
53
+ Validated against the obytes Expo template bake-off: the login-form suite (previously import-time dead) now passes, 34/40 → 38/40 overall with the two remaining failures pre-existing and unrelated (bottom-sheet mock completeness).
54
+
55
+ - 1a3bcea: New CLI: `npx vitest-native init | doctor | migrate`.
56
+
57
+ - **`init`** writes a ready-to-run Vitest config (`--jest-compat` for the exact jest-compat block the migration guide documents; refuses to overwrite without `--force`).
58
+ - **`doctor`** diagnoses the environment read-only: Node floor (including the RNTL 14 ⇄ Node 22.13 interaction, which previously surfaced only as a raw runtime failure), required peers against supported ranges, which engine `auto` resolves to and why, every auto-detected preset, Expo presence with known-limits pointer, and config presence. Exits non-zero on blocking problems.
59
+ - **`migrate`** analyzes the project's Jest configuration (`package.json#jest` or `jest.config.{js,cjs,json}`) and reports key-by-key what maps automatically (setup files, path aliases, `transformIgnorePatterns` allowlists → `transform: [...]`, timeouts, mock hygiene flags), what the auto-detected presets already cover (deletable manual `__mocks__` and setup lines), what needs a human, and what drops — ending with a complete suggested config. Dry-run by default; `--write` saves it. Test files are never edited (`jestMockTransform()` handles top-level `jest.mock` at runtime).
60
+
61
+ The packed-tarball consumer suite exercises the bin end-to-end (`npx vitest-native doctor|migrate`).
62
+
63
+ - ac70dec: Precompile React Native's require graph so isolated test files stop paying to re-load it
64
+
65
+ The native engine runs React Native's real JavaScript, and with isolation on — the
66
+ default — that graph was re-instantiated for every test file: roughly 440 separate
67
+ Node module loads each time, one per RN source file. Measured on RN 0.86, that cost
68
+ ~59ms for a typical test's slice of React Native and ~110ms for the full public API,
69
+ per file.
70
+
71
+ React Native's graph is now walked once per (RN version × platform × Babel
72
+ toolchain) and emitted as a single file of lazy per-module factories with every
73
+ require target resolved ahead of time. A test file pays one read and one compile
74
+ instead of ~440. The registry is built in the Vite process, so the cost is paid once
75
+ per run, and it is cached under `node_modules/.cache/vitest-native` keyed by a
76
+ manifest of the files it was built from — a reinstalled or patched React Native
77
+ rebuilds it rather than serving stale code.
78
+
79
+ Measured on this repository's native suite: aggregate import time 8.8s → 1.9s
80
+ (4.6×), wall clock 1.81s → 1.05s.
81
+
82
+ Semantics are unchanged by design. Module identity is preserved, so React Native's
83
+ singletons behave exactly as before and a deep `react-native/Libraries/...` require
84
+ from an ecosystem package resolves to the same instance the app sees. Laziness is
85
+ preserved, so a test that touches `View` and `StyleSheet` still does not execute the
86
+ rest of React Native. Anything the registry cannot serve — a computed require, a
87
+ module outside the entry graph, a package listed in `transform` — falls through to
88
+ the per-file loader hooks, and a registry that cannot be built leaves the engine
89
+ running exactly as it did before.
90
+
91
+ - ac70dec: `vi.mock('react-native')` now works under the native engine
92
+
93
+ React Native runs in Node's module graph under `engine: 'native'`, which put it
94
+ outside Vitest's module registry — so `vi.mock('react-native', …)`, the single most
95
+ common thing an existing Jest suite does, silently had no effect. It was the most
96
+ frequently hit blocker when moving a real suite over.
97
+
98
+ The app and test graph now import React Native through a facade module the plugin
99
+ serves. The facade re-exports the same instances Node's graph holds, so React
100
+ Native's behaviour and object identity are unchanged — an externalized library and
101
+ your test still see the very same `Dimensions`, `Platform`, and `StyleSheet`. What
102
+ changes is that Vitest owns the module id, which is what lets it intercept:
103
+
104
+ ```ts
105
+ vi.mock("react-native", async (importOriginal) => ({
106
+ ...(await importOriginal<typeof import("react-native")>()),
107
+ Alert: { alert: vi.fn() },
108
+ }));
109
+ ```
110
+
111
+ `importOriginal()` returns real React Native, everything left unmocked stays real,
112
+ and components still render React Native's own host components (`RCTView`, not a
113
+ stand-in).
114
+
115
+ One limit worth knowing: the interception covers modules in your project's graph —
116
+ your app and test code. A third-party package that Vitest externalizes resolves
117
+ React Native through Node and will still see the unmocked module. Add such a package
118
+ to `transform: [...]` if its view of React Native needs to be mocked too.
119
+
120
+ - ac70dec: Support Vitest 5
121
+
122
+ The peer range widens from `>=4 <5` to `>=4 <6`. Nothing in the package needed to
123
+ change for it: the native engine, the mock engine, the precompiled React Native
124
+ registry, the `react-native` facade, and the hot runtime all run unmodified on Vitest
125
+ 5, including its `@experimental` worker API.
126
+
127
+ The claim is backed the same way the Vitest 4 support is. The CI matrix gains a
128
+ Vitest 5 column — run against the oldest and newest supported React Native, since it
129
+ varies the runner rather than RN — and it is blocking, because a declared peer range
130
+ is a promise about every release inside it. Each cell runs the native suite stock and
131
+ hot plus the mock-vs-real-RN cross-check, exactly as the Vitest 4 columns do.
132
+
133
+ While 5.x is still prerelease it is reachable only through its `beta` tag; the
134
+ repository's install-age policy still applies, so CI resolves the newest beta at least
135
+ a week old rather than whatever published that day.
136
+
137
+ - 2d07b7a: Add a built-in `react-native-worklets` preset (auto-detected). Worklets is Reanimated's low-level runtime and is also imported directly by apps (e.g. `import { scheduleOnUI } from 'react-native-worklets'`). It ships a Jest mock at `react-native-worklets/lib/module/mock` that is ESM ending in `module.exports = …`; under the native engine React Native and its ecosystem are externalized, so requiring that file through Node throws `module is not defined in ES module scope` and takes down the whole test file. The preset shadows the package with a self-contained mock modelled on worklets' own `mock.js` API (schedulers run their worklet synchronously, matching the Reanimated preset), so worklets-using suites load and render without a hand-written mock.
138
+
139
+ ### Patch Changes
140
+
141
+ - e49168e: Bound hot-runtime memory by default. When `hotRuntime` is enabled on the native engine and neither `memoryLimit` nor `recycleAfterFiles` is configured, a default per-worker memory ceiling of `clamp(totalmem * 0.25, 768MB, 1.5GB)` is now applied. Hot workers keep React Native resident and accumulate roughly 4 MB per file, so without a bound a long suite could grow toward OOM; the default lets multi-worker runs recycle a worker once it crosses the ceiling, keeping total memory bounded out of the box.
142
+
143
+ An explicit `memoryLimit` or `recycleAfterFiles` is respected unchanged. Single-worker hot still cannot recycle (Vitest batches all files into one scheduler task), so the bound is inert there and the existing one-time "recycling INACTIVE" warning advises running with `maxWorkers >= 2`.
144
+
145
+ - 0d38401: Fix two `mock` engine divergences from real React Native, found by the behavioral cross-check:
146
+
147
+ - `Pressable` now resolves function `style` and `children` (`({ pressed }) => …`) against its press state, matching real RN's resting render and updating while pressed. Previously the functions were passed through untouched, so the style was never applied and function children never rendered.
148
+ - `processColor()` returns `undefined` for an unparseable color (matching real RN's normalizer) instead of coercing to opaque black.
149
+
150
+ Also publishes the cross-check as a generated, drift-guarded fidelity report — a live badge and a docs page listing the full corpus and what is deliberately left ungated — and expands the corpus to 75 probes.
151
+
152
+ - 6c29566: Expand the "Migrating from Jest" guide with the empirically-derived limits of a real migration: a "Known limits" section covering assertions coupled to Jest's RN mock internals that don't port under a real-RN engine (`jest.spyOn(View.prototype, …)`, mocks of RN internal submodules, raw `source`-shape assertions, `jest.mock` nested in callbacks), an Expo-core caveat, and concrete guidance for the `transformIgnorePatterns` → `transform` allowlist (including the JSX-in-`.js` third-party-lib parse error and its fix).
153
+ - ac70dec: Narrow the mock engine's Flow-strip, and stop `migrate` opting packages out of auto-compilation
154
+
155
+ **Flow-strip targeting.** The mock engine compiles React Native ecosystem packages
156
+ pulled into the Vite graph, selected by testing for `react-native` anywhere in the
157
+ file's path. That also matched every dependency of a project in a directory called
158
+ `react-native-app`, and packages like `eslint-plugin-react-native` — running a Flow
159
+ parser over files with nothing to do with React Native. It now matches the package
160
+ name after `node_modules`: a name beginning with `react-native` (scoped or not, so
161
+ `@shopify/react-native-skia` counts) or a scope beginning with `@react-native`.
162
+ Everything the substring test legitimately caught is still caught, and nothing else
163
+ is.
164
+
165
+ **`npx vitest-native migrate`.** It translated Jest's `transformIgnorePatterns` into
166
+ `transform: [...]` entries for packages the engine now detects and compiles by itself.
167
+ That was worse than redundant: an explicit `transform` entry takes precedence, so the
168
+ suggested config would have opted those packages back out of inlining, losing
169
+ `vi.mock` support for no gain. Packages declaring `react-native` are now reported as
170
+ already handled.
171
+
172
+ Also adds a test that the plugin's virtual `react-native` module exports exactly what
173
+ the mock provides — the two lists were in step, but only by hand.
174
+
175
+ - f6c4c5b: Provide `SourceCode.getConstants().scriptURL` at the native boundary. RN's `getDevServer` (`Libraries/Core/Devtools/getDevServer.js`) reads `scriptURL` and calls `.match()` on it; under the native engine the value was `undefined`, so `getDevServer` threw and took down any test whose module graph reached it. The boundary now returns a `file://` (bundled) URL for the `SourceCode` native module. It is deliberately not an `http(s)` URL: `getDevServer` only treats `http(s)` script URLs as a live dev server, so a `file://` value keeps `bundleLoadedFromServer` false — tests run as if loaded from a bundle rather than a Metro dev server, which prevents RN internals and third-party SDKs from believing they're connected to a packager and attempting real network I/O against `localhost:8081`. This mirrors the intent of RN's own Jest mock (which keeps that flag off).
176
+ - ac70dec: Explain why `engine: 'native'` cannot run on a VM pool
177
+
178
+ Now that a configured `pool` is respected rather than overridden, `vmThreads` and
179
+ `vmForks` reach the native engine — where they cannot work. VM pools execute test code
180
+ in a `vm` context whose module executor bypasses Node's loader, and `module.register()`
181
+ (how the engine installs the ESM hook that Flow-strips React Native and resolves its
182
+ platform files) throws there outright. The failure surfaced far from its cause, as
183
+ `Platform.OS` being undefined deep inside `NativeEventEmitter`.
184
+
185
+ The plugin now refuses at config time and names the alternatives: `threads` (the
186
+ default), `forks`, or `engine: 'mock'`, which needs no hooks.
187
+
188
+ - ac70dec: Stop overriding a configured `pool`, and refuse a mismatched Vitest instead of reporting nothing
189
+
190
+ Two fixes to the native engine's pool handling.
191
+
192
+ **A configured `pool` is no longer discarded.** A plugin's `config()` result is merged
193
+ over the user's config, and the native engine returned `pool: 'threads'`
194
+ unconditionally — so a project asking for `forks`, `vmThreads`, or its own custom pool
195
+ silently got `threads`, with no warning and no way to tell from the outside. `threads`
196
+ is now only a default, applied when no pool was configured. (`hotRuntime` still
197
+ supplies its own pool, since opting into it _is_ choosing one, and now warns when that
198
+ overrides a configured pool.)
199
+
200
+ **`hotRuntime` now fails loudly when its worker would load a different Vitest.** The
201
+ hot worker entry ships inside vitest-native, so its `import 'vitest/worker'` resolves
202
+ from this package's location rather than the project's. Where a monorepo has more than
203
+ one Vitest install — a linked package, a hoisted `node_modules`, mixed versions across
204
+ workspaces — the worker and the host end up on different installations. Nothing about
205
+ that was visible: the start handshake succeeded, the run request was accepted, no
206
+ result was ever reported, and Vitest printed "No test files found" with no error at
207
+ all. The pool now compares the two resolved paths at config time and throws, naming
208
+ both, rather than letting a run pass having tested nothing.
209
+
210
+ - ac70dec: Resolve React Native package entries the way Metro does
211
+
212
+ Both engines set `resolve.conditions: ['react-native']`, which governs Vite's _client_
213
+ environment. Vitest runs tests in the **ssr** environment, which keeps its own list —
214
+ Vite drops both `conditions` and `mainFields` when deriving it — so neither was ever
215
+ applied to anything a test imported.
216
+
217
+ Any package shipping a distinct React Native build behind that condition therefore
218
+ loaded its web build instead:
219
+
220
+ ```jsonc
221
+ "exports": { ".": { "react-native": "./native.js", "default": "./web.js" } }
222
+ ```
223
+
224
+ The same held for the legacy mechanism, still used by packages published before
225
+ `exports`:
226
+
227
+ ```jsonc
228
+ "main": "./web.js", "react-native": "./native.js"
229
+ ```
230
+
231
+ Metro resolves both ahead of the standard fields, so tests were exercising code the
232
+ app never runs, with nothing to indicate it. Both are now set for the ssr environment
233
+ as well as the client one, under both engines, with a regression test each.
234
+
235
+ `browser` is deliberately not added to `mainFields` even though Metro lists it: under
236
+ Node it would pull the web build of any package that has a browser field and no
237
+ react-native one.
238
+
239
+ **Upgrade note.** The `react-native` field is honoured wherever it appears, not only
240
+ on React Native libraries — Algolia's clients, `nanoid` and `msgpackr` all ship one,
241
+ usually pointing at a browser or ESM build. Metro resolves those the same way, so this
242
+ is the build the app actually runs, but a dependency may now load a different file
243
+ than it did before. If that is a problem for one package, `transform: ['the-package']`
244
+ or an explicit `resolve.alias` pins it.
245
+
246
+ - ac70dec: Fix a stale-registry hazard and restore React Native's stack frames
247
+
248
+ Two defects in the precompiled registry, both found by reviewing it adversarially
249
+ rather than by a failing test.
250
+
251
+ **The cache key ignored the boundary mocks' content.** It hashed their module _names_,
252
+ but the mocks are compiled into the registry, so changing one — a maintainer editing a
253
+ mock, or a user upgrading to a release that changed one — left the cached registry
254
+ valid and kept serving the previous behaviour with nothing to indicate it. The key now
255
+ hashes the rendered mock source, and this package's own version alongside it, covering
256
+ everything else it contributes.
257
+
258
+ **Stack frames from inside React Native lost their file.** Collapsing ~440 modules
259
+ into one file meant an RN-internal failure reported
260
+ `registry/rn-ios-<hash>.cjs:253:7638` instead of
261
+ `Libraries/Animated/nodes/AnimatedInterpolation.js` — the useful part of the frame.
262
+ The registry now emits a source map attributing every generated line to the React
263
+ Native file it came from, and enables Node's source-map support before compiling
264
+ itself. Failure output names real React Native files again, at no runtime cost.
265
+
266
+ Also relaxes the `hotRuntime` Vitest guard added alongside it: it compared resolved
267
+ paths, so a monorepo with the same Vitest version installed in two trees was refused
268
+ even though those interoperate fine. Only a version difference is an error now.
269
+
270
+ - 4c567c1: Make native-engine turboStubs identity-stable and spy-able. Unmocked native modules were served by a Proxy that minted a fresh stub object on every property access and whose get trap never consulted the target — so `NativeModules.Foo !== NativeModules.Foo`, and `vi.spyOn(NativeModules.Foo, 'method')` silently recorded nothing (the spy landed on a throwaway object). Stubs are now memoized per module name in the shared boundary state (`NativeModules.Foo === TurboModuleRegistry.get('Foo')`, matching bridgeless RN), methods are memoized on first read, and explicitly-set properties win — so spies record and restore correctly. A `has` trap reports all properties present, consistent with the get trap's serve-anything behavior, which `vi.spyOn`'s existence check requires. Under the hot runtime, per-file overrides (spies, memoized methods) are cleared between files via the surgical-reset registry while stub identity is preserved for resident libraries holding references.
271
+ - 57f155d: Fix three silent resolution-fidelity gaps around deep (subpath) imports.
272
+
273
+ - **`react-native` subpath default exports are now the leaf module.** `import Platform from 'react-native/Libraries/Utilities/Platform'` previously received the entire mock object as `Platform`, so `Platform.OS` was silently `undefined`. The virtual subpath modules (ESM) and the CJS bridge now derive the intended export from the subpath's basename and serve it as the default — CJS requires get Babel-interop shape (`{ __esModule, default }` via a live wrapper) so both `require('.../Platform').OS` and `_interopRequireDefault(...)` consumers work. Unknown leaves keep the previous whole-mock fallback.
274
+ - **`react-native/package.json` (and preset `pkg/package.json`) resolve to the real manifest.** Version gates like `require('react-native/package.json').version` previously read the mock and got `undefined`. Both the Vite-graph and CJS-bridge interception now exempt the manifest; when the package is not installed, the previous mock fallback is kept rather than erroring.
275
+ - **Preset shadowing now covers subpath imports.** `import Swipeable from 'react-native-gesture-handler/Swipeable'` (and CJS equivalents, including requires nested inside externalized third-party libraries) previously bypassed the preset mock entirely and loaded the package's real native-runtime code — or failed resolution outright on package versions that no longer ship the deep file. All three redirect layers (Vite plugin, ESM loader hook, CJS require hook) now match subpaths of preset packages and serve the mock export named by the subpath's leaf, falling back to the root mock. JSON and asset-extension subpaths are exempt so manifests and font/image files keep resolving from disk. CJS interop wrappers are memoized per specifier (keyed by the live mock set, so hot-runtime per-file rebuilds stay correct) to keep module identity stable across repeated requires.
276
+
277
+ - 3b1c396: Native-engine transform cache rework: project-local, content-keyed, lazy Babel.
278
+
279
+ - **The transform disk cache moves from `os.tmpdir()` to the project's `node_modules/.cache/vitest-native/`** (tmpdir fallback when node_modules is absent or unwritable). tmpdir is ephemeral on CI runners — every job paid a full cold Babel transform of React Native's ~250-file boot graph — and macOS purges it periodically. The new location persists across runs and is restorable by standard CI dependency-cache actions. The V8 compile cache is colocated.
280
+ - **Disk entries are keyed by content hash (platform + path + source), not mtime + size.** Content keys survive fresh installs, Docker mtime normalization, and CI cache restores — and eliminate the stale-hit class where a same-size, same-mtime file with different content served wrong executable code. The path stays in the key because Babel's output embeds the filename (`_jsxFileName` in transformed JSX), so identical sources at different paths must not share an entry; restores are valid wherever the checkout path is stable, which CI workspaces are. The cache directory name now also carries the `@babel/core` version alongside the preset version, so a Babel upgrade invalidates cleanly.
281
+ - **`@babel/core` loads lazily, only on a cache miss.** Loading Babel costs ~35ms vs ~0.5ms for the resolve-only version check, and under the default engine every isolated worker paid it even when every file came from the disk cache. Measured on the package's own native suite (warm cache): aggregate worker setup down ~30%, wall clock ~11% — the effect scales with test-file count.
282
+
283
+ - ac70dec: Match `transform: [...]` packages by their real location, not by name anywhere in the path
284
+
285
+ The pattern behind `transform` tested for `/<package-name>/` anywhere in a file's
286
+ path, so any **directory** sharing a package's name was treated as that package. A
287
+ project folder called `expo`, or a source directory named after the library it
288
+ implements, made every file beneath it get compiled and externalized as third-party
289
+ source — including, in one case, this package's own runtime, which then failed with
290
+ `Vitest cannot be imported in a CommonJS module using require()`.
291
+
292
+ A file now matches only if it is inside the package's resolved directory, or under
293
+ `node_modules/<name>/`. Both rules are needed: the resolved directory covers workspace
294
+ and `file:` dependencies, which resolve to a real path with no `node_modules` segment,
295
+ while the `node_modules` rule covers additional copies of a package that a single
296
+ resolution cannot see.
297
+
298
+ - 091a572: Three hardening fixes:
299
+
300
+ - **Prerelease peer versions no longer fail validation.** A prerelease sharing the minimum's major.minor (e.g. vitest `4.0.0-beta.3` against the `4.0.0` floor) parsed with `NaN` in the patch slot, failed the minimum check, and hard-errored at startup for installs running betas/RCs. Prerelease/build metadata is now stripped before comparison; a prerelease of the minimum itself is accepted.
301
+ - **Mock-engine asset stubs match the native loader's semantics.** The extension match is now case-insensitive (`LOGO.PNG` stubs like `logo.png`), user-supplied `assetExts` entries are regex-escaped, and the stubbed basename is JSON-stringified so filenames containing quotes emit valid JS.
302
+ - **The mock engine's Flow-strip transform skips unparseable files instead of throwing.** The `@flow` filter is a heuristic — the marker can appear inside a string or comment of a file `flow-remove-types` then fails to parse; that parse error previously took down the whole transform pipeline.
303
+
304
+ - ac70dec: Fix `importOriginal()` inside a test's own `vi.mock('react-native')` under the mock engine
305
+
306
+ A test that registered its own `vi.mock('react-native', …)` replaced the registration
307
+ the setup file makes, and the factory's `importOriginal()` then resolved to an empty
308
+ module. The near-universal spread-and-override form therefore dropped every export
309
+ the test did not name:
310
+
311
+ ```ts
312
+ vi.mock("react-native", async (importOriginal) => ({
313
+ ...(await importOriginal()), // was empty
314
+ Alert: { alert: vi.fn() },
315
+ }));
316
+ // -> No "Platform" export is defined on the "react-native" mock
317
+ ```
318
+
319
+ The virtual `react-native` module now re-exports the runtime mock, so
320
+ `importOriginal()` returns the full surface and unnamed exports survive.
321
+
322
+ - ac70dec: Stop the hot runtime's legacy-runner import from breaking on Vitest 5
323
+
324
+ `hotRuntime`'s test runner imported `vitest/runners` as a fallback for Vitest 4.0.x,
325
+ guarded by a runtime check. The guard does not help: a literal specifier is resolved
326
+ when the module is transformed, not when the branch runs. Vitest 5 removed that
327
+ subpath, so the resolve failed on every test file — and the failure mode was the worst
328
+ kind, reporting unhandled errors, running no tests, and still exiting 0.
329
+
330
+ The fallback specifier is now computed, so it stays invisible to the resolver: Vitest
331
+ 4.0.x keeps its fallback and Vitest 5 never looks for it.
332
+
333
+ - a756f6a: Make `jest.requireActual('react-native')` return a writable facade. Jest suites commonly clone-and-override React Native — `const RN = jest.requireActual('react-native'); RN.Platform = {...}; return RN`. Under the native engine RN's index is a facade of lazy getters with no setters, so assigning to it threw `Cannot set property … which has only a getter` and failed to load the whole test file. `requireActual('react-native')` now returns a write-through proxy: reads fall through to the real (lazy) facade, and assignments are captured so the override wins on later reads — matching Jest's mutable module. Only `react-native` is wrapped; its submodules and other packages are ordinary mutable CommonJS.
334
+
3
335
  ## 0.8.0
4
336
 
5
337
  ### Minor Changes
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # vitest-native
2
2
 
3
+ [![RN fidelity](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fdanfry1%2Fvitest-native%2Fmain%2Fpackages%2Fvitest-native%2Fcrosscheck%2Ffidelity-badge.json)](https://github.com/danfry1/vitest-native/blob/main/website/guide/fidelity.md)
4
+
3
5
  Run your React Native tests under Vitest, against **real React Native** — the same JavaScript that ships in your app, with only the native-module boundary mocked. That is the default and the point of the project. A lightweight pure-JS mock engine is available as an opt-in for fast, RN-free unit tests.
4
6
 
5
7
  > **Beta.** The release-supported native engine is validated across React Native 0.81–0.86,
@@ -217,6 +219,18 @@ the app/test module graph for every file. It also restores direct `process.env`
217
219
  file-created globals, RN event subscriptions, dimensions, timers, and plugin mock state between
218
220
  files. A dedicated one-worker CI test exercises this cross-file isolation contract.
219
221
 
222
+ **Known limitation.** Because React Native stays resident, state held inside React Native's own
223
+ internal modules is _not_ reset between files — the per-file reset deliberately does not reach into
224
+ third-party or RN-internal module internals, because doing so generically is unsafe. Suites that
225
+ lean on deep resident-RN-internal state can therefore see cross-file interference under the hot
226
+ runtime that they would not see under the default per-file isolation. The clearest example is heavy
227
+ cross-file `Animated` usage, where animations driven in one file can alter how a later file renders.
228
+ The tell-tale sign is a test that passes in isolation but fails when run after other files; if you
229
+ see that, move the affected suite (or the project) back to the default per-file isolation. This is
230
+ why the hot runtime is opt-in and experimental rather than the default; closing the gap for all
231
+ suites depends on a per-file module reset inside a persistent worker that Vitest does not yet
232
+ provide.
233
+
220
234
  For additional leak containment:
221
235
 
222
236
  ```ts
@@ -833,7 +847,7 @@ Every release must pass:
833
847
 
834
848
  - Linux on Node 20.19 and 22.13, plus macOS and Windows on Node 22.13.
835
849
  - The mock, native iOS, native Android, hot-runtime, isolation, and 100-file soak suites.
836
- - React Native 0.81–0.85 against both locked and newest-supported Vitest 4.
850
+ - React Native 0.81–0.86 against both locked and newest-supported Vitest 4.
837
851
  - Packed bare RN 0.83/RNTL 12, Expo 56/RNTL 13, Vite 8 monorepo/RNTL 14, and RN 0.86 consumers.
838
852
  - Mock-versus-real-RN behavioral cross-checks, example-app tests, typecheck, lint, formatting, and
839
853
  package export analysis.