vitest-native 0.14.0-rc.9 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +94 -961
  2. package/dist/cli.d.mts +1 -3
  3. package/dist/cli.mjs +286 -97
  4. package/dist/context.d.mts +45 -0
  5. package/dist/context.mjs +243 -0
  6. package/dist/errors.d.mts +3 -0
  7. package/dist/helpers.cjs +53 -4
  8. package/dist/helpers.d.cts +1 -3
  9. package/dist/helpers.d.mts +1 -3
  10. package/dist/helpers.mjs +2 -3
  11. package/dist/host-BAAAlSkO.mjs +1028 -0
  12. package/dist/{index-CzQazgp9.d.cts → index-aNBCTfA5.d.mts} +35 -55
  13. package/dist/index.d.mts +1 -3
  14. package/dist/index.mjs +463 -595
  15. package/dist/jest-compat/error-equality.mjs +127 -0
  16. package/dist/jest-compat/jest-object.mjs +149 -4
  17. package/dist/jest-compat/node-registry.mjs +233 -58
  18. package/dist/jest-compat/setup.mjs +28 -4
  19. package/dist/jest-compat.cjs +227 -52
  20. package/dist/jest-compat.d.cts +5 -6
  21. package/dist/jest-compat.d.mts +5 -6
  22. package/dist/jest-compat.mjs +204 -52
  23. package/dist/matchers.cjs +1 -2
  24. package/dist/matchers.d.cts +0 -2
  25. package/dist/matchers.d.mts +0 -2
  26. package/dist/matchers.mjs +1 -2
  27. package/dist/{memory-FYbP0_gg.mjs → memory-Couw0Esx.mjs} +31 -6
  28. package/dist/native/assets.d.mts +2 -0
  29. package/dist/native/assets.mjs +34 -0
  30. package/dist/native/babel-toolchain.mjs +190 -0
  31. package/dist/native/babel-worker.mjs +47 -0
  32. package/dist/native/boundary.mjs +23 -8
  33. package/dist/native/compile-cache.mjs +21 -9
  34. package/dist/native/coverage-v8.mjs +287 -0
  35. package/dist/native/esm-interop.mjs +216 -0
  36. package/dist/native/expo-native-modules.mjs +7 -1
  37. package/dist/native/globals.mjs +104 -6
  38. package/dist/native/hooks.mjs +278 -61
  39. package/dist/native/loader.mjs +390 -23
  40. package/dist/native/match.d.mts +24 -2
  41. package/dist/native/match.mjs +117 -12
  42. package/dist/native/metro-profile-compiler.mjs +2 -31
  43. package/dist/native/module-reset.mjs +37 -5
  44. package/dist/native/native-modules.d.mts +2 -3
  45. package/dist/native/native-modules.mjs +22 -21
  46. package/dist/native/ownership.d.mts +10 -0
  47. package/dist/native/ownership.mjs +96 -9
  48. package/dist/native/registry-compiler.mjs +6 -0
  49. package/dist/native/registry.mjs +138 -119
  50. package/dist/native/resident-health.mjs +133 -0
  51. package/dist/native/resolve.d.mts +6 -0
  52. package/dist/native/resolve.mjs +119 -9
  53. package/dist/native/rntl-hooks.mjs +157 -6
  54. package/dist/native/rntl-text-host.mjs +64 -0
  55. package/dist/native/runner.mjs +73 -0
  56. package/dist/native/setup.mjs +96 -70
  57. package/dist/native/state-manifest.mjs +14 -8
  58. package/dist/native/transform.d.mts +2 -0
  59. package/dist/native/transform.mjs +476 -59
  60. package/dist/native/worker.mjs +65 -36
  61. package/dist/{pool-DjpOjOf3.mjs → pool-CFSpNfyw.mjs} +37 -11
  62. package/dist/{preset-map-BlBriTA0.mjs → preset-map-CogjYmSw.mjs} +4 -19
  63. package/dist/preset-modules.mjs +2 -11
  64. package/dist/{presets--zrEWQC2.mjs → presets-CXDyg51l.mjs} +65 -82
  65. package/dist/presets.d.mts +1 -1
  66. package/dist/presets.mjs +1 -1
  67. package/dist/report-error.d.mts +20 -0
  68. package/dist/report-error.mjs +145 -0
  69. package/dist/rntl-support.d.mts +12 -0
  70. package/dist/rntl-support.mjs +189 -0
  71. package/dist/{rolldown-runtime-BhDjJH2R.mjs → rolldown-runtime-D70C1uOS.mjs} +1 -2
  72. package/dist/serializer.cjs +1 -2
  73. package/dist/serializer.d.cts +1 -3
  74. package/dist/serializer.d.mts +1 -3
  75. package/dist/serializer.mjs +1 -2
  76. package/dist/setup.mjs +95 -156
  77. package/dist/{worker-vitest-BGPo0ek6.mjs → worker-vitest-CILPFeRX.mjs} +2 -3
  78. package/docs/migrating-from-jest.md +82 -16
  79. package/docs/release-readiness.md +1 -1
  80. package/package.json +119 -102
  81. package/CHANGELOG.md +0 -2491
  82. package/dist/cli.cjs +0 -1951
  83. package/dist/cli.d.cts +0 -3
  84. package/dist/ecosystem-D6e1OVOg.mjs +0 -1019
  85. package/dist/ecosystem-MFwkbnaC.cjs +0 -1099
  86. package/dist/errors-B3lJK46O.cjs +0 -75
  87. package/dist/errors-CxoBUfVJ.mjs +0 -64
  88. package/dist/index-xw43lBlv.d.mts +0 -481
  89. package/dist/memory-6EPHrJA1.cjs +0 -144
  90. package/dist/pool-B4yesGhI.cjs +0 -121
  91. package/dist/preset-map-jSFsNy1Q.cjs +0 -241
  92. package/dist/preset-modules-BoLkaeEN.cjs +0 -53
  93. package/dist/preset-modules-CG8-G82P.mjs +0 -36
  94. package/dist/presets-9f83H0WW.cjs +0 -3939
  95. package/dist/rolldown-runtime-C0BPl7ul.cjs +0 -43
  96. package/dist/worker-vitest-BfiQB8ND.cjs +0 -62
  97. package/docs/hot-default-design.md +0 -216
package/README.md CHANGED
@@ -1,95 +1,71 @@
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)
3
+ [![npm](https://img.shields.io/npm/v/vitest-native)](https://www.npmjs.com/package/vitest-native)
4
+ [![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://danfry1.github.io/vitest-native/guide/fidelity)
5
+ [![license](https://img.shields.io/npm/l/vitest-native)](https://github.com/danfry1/vitest-native/blob/main/LICENSE)
4
6
 
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.
7
+ **Test React Native with Vitest, against real React Native.**
6
8
 
7
- > **Beta.** The release-supported native engine is validated across React Native 0.81–0.88,
8
- > Vite 6–8, Vitest 4–5, RNTL 12–14, bare apps, Expo SDK 58 and 57 (including expo-router's own testing
9
- > library), and hoisted monorepos. The hot
10
- > runtime (on by default where it can be bounded) is marked experimental because it uses Vitest's
11
- > experimental custom-pool APIs.
12
- >
13
- > Maintained successor to [`vitest-community/vitest-react-native`](https://github.com/vitest-community/vitest-react-native) — same core idea (externalize RN, run its real JS under Node), rebuilt for modern Vitest (4+). Coming from it? See [Migrating from `vitest-react-native`](#migrating-from-vitest-react-native).
9
+ vitest-native is a Vitest plugin. Your tests run React Native's real JavaScript, the same code
10
+ that ships in your app, and only the native modules and native host components are mocked.
11
+ It works the same for bare React Native and Expo apps.
14
12
 
15
- ---
13
+ **📖 Documentation: [danfry1.github.io/vitest-native](https://danfry1.github.io/vitest-native/)**
16
14
 
17
- ## Table of Contents
15
+ ## Why not Jest's preset?
18
16
 
19
- - [Why vitest-native?](#why-vitest-native)
20
- - [Installation](#installation)
21
- - [Quick Start](#quick-start)
22
- - [Plugin Options](#plugin-options)
23
- - [Mocked Components and APIs](#mocked-components-and-apis)
24
- - [React Native Test Suite Conformance](#react-native-test-suite-conformance)
25
- - [Test Helpers](#test-helpers)
26
- - [Auto-Detect Presets](#auto-detect-presets)
27
- - [Migrating from `vitest-react-native`](#migrating-from-vitest-react-native)
28
- - [Migrating from Jest](#migrating-from-jest)
29
- - [Troubleshooting](#troubleshooting)
30
- - [RNTL Matchers](#rntl-matchers)
31
- - [Animated Matchers (Reanimated)](#animated-matchers-reanimated)
32
- - [Snapshot Serializer](#snapshot-serializer)
33
- - [Platform Extensions](#platform-extensions)
34
- - [Assets](#assets)
35
- - [Diagnostics](#diagnostics)
36
- - [Support Policy](#support-policy)
37
- - [Requirements](#requirements)
38
- - [License](#license)
17
+ Jest's React Native preset also runs real React Native JavaScript, but it swaps the core components
18
+ (`View`, `Text`, `ScrollView`, `TextInput`, `Image`, `Modal`) for simple stand-ins. vitest-native's
19
+ mock boundary sits lower, so your tests run React Native's real component code.
39
20
 
40
- ---
21
+ | | Jest + RN preset | vitest-native |
22
+ |---|---|---|
23
+ | Core components (`View`, `Text`, …) | Stand-ins | Real |
24
+ | Native modules and host components | Mocked | Mocked |
25
+ | Rendered host names | `View`, `Text` | `RCTView`, `RCTText` |
41
26
 
42
- ## Why vitest-native?
27
+ A lightweight pure-JS mock engine is also available (`engine: 'mock'`) for tests that need no React
28
+ Native at all. See the [comparison with Jest](https://danfry1.github.io/vitest-native/guide/comparison) and
29
+ [choosing an engine](https://danfry1.github.io/vitest-native/guide/engines).
43
30
 
44
- Testing React Native code with Jest has traditionally required a patchwork of configuration: custom transformers, manual mock files, preset packages, and brittle `jest.setup.js` scripts that break across React Native versions. Each new library (Reanimated, Gesture Handler, Safe Area, Navigation) adds another mock to maintain.
31
+ ## Who it's for
45
32
 
46
- `vitest-native` replaces all of that with a single Vite plugin:
33
+ - **New React Native projects, and new tests.** There is nothing to migrate.
34
+ - **Teams that want real-React-Native fidelity** in component, accessibility and integration tests.
35
+ - **Teams already on Vitest** for web or server code who want one runner.
36
+ - **Teams adopting incrementally:** new tests run on vitest-native while an existing Jest suite
37
+ keeps running.
47
38
 
48
- - **Real React Native, by default.** `reactNative()` with no options runs React Native's real JavaScript — the same source that ships in your app — mocking only the native-module boundary. Jest's preset replaces many components and modules (`View`, `Text`, `ScrollView`, `Linking`, `AccessibilityInfo`, `Image`, …) with stubs; vitest-native runs the real ones. See [`engine`](#engine).
49
- - **The runner you already use.** Already on Vitest for web? Write your React Native tests in the same runner — same config patterns, native ESM, watch mode, and UI. One test stack across web and native.
50
- - **No Jest config patchwork.** Add one plugin instead of custom transformers, `transformIgnorePatterns`, and brittle `jest.setup.js` mock files.
51
- - **Auto-detect presets.** The plugin scans your `node_modules` and shadows native-runtime libraries (Reanimated, Gesture Handler, Safe Area, Navigation) automatically — under both engines.
52
- - **Opt-in mock engine.** Prefer no React Native at all for a pure-logic suite? `engine: 'mock'` reimplements RN in pure JS with **zero extra dependencies**. It is the escape hatch, not the headline — see [Choosing an engine](#engine).
39
+ Migrating a large Jest suite is incremental, not turnkey.
53
40
 
54
- > **Coming from Jest?** This is not a drop-in swap. New tests are friction-free; an existing Jest suite needs porting off `@react-native/jest-preset`, `@jest/globals`, and `jest.mock('react-native')`. See [Migrating from Jest](#migrating-from-jest). Coming from `vitest-react-native`? You are already vitest-shaped — migration is close to a package swap.
41
+ ## Proof
55
42
 
56
- ---
43
+ - **Behavioral cross-check.** The same probes run under the mock engine and under real React
44
+ Native, across every React Native version CI supports, and any difference fails the build. The
45
+ badge above shows the current count; the [fidelity report](https://danfry1.github.io/vitest-native/guide/fidelity) lists every probe.
46
+ - **Packed consumers in CI.** The release tarball is installed into bare React Native, Expo SDK 57
47
+ and 58 apps (with expo-router), and npm and pnpm workspace monorepos, and their tests run in CI.
48
+ - **Real apps, as observations.** Public apps are run in the
49
+ [bake-offs repository](https://github.com/danfry1/vitest-native-bakeoffs), with each app's setup
50
+ in the repository. Their results are not capability claims; see the
51
+ [validation model](https://danfry1.github.io/vitest-native/guide/validation-model).
52
+ - **Performance.** vitest-native is not a speed play. Each test file gets a fresh worker by
53
+ default; the opt-in hot runtime reuses workers, and whether that is faster depends on your suite,
54
+ so measure it.
57
55
 
58
- ## Installation
56
+ ## Quick start
59
57
 
60
58
  ```bash
61
- # bun
62
- bun add -d vitest-native
63
-
64
- # npm
65
- npm install -D vitest-native
66
-
67
- # yarn
68
- yarn add -D vitest-native
69
-
70
- # pnpm
71
- pnpm add -D vitest-native
72
- ```
73
-
74
- A real React Native project already provides what the native engine needs —
75
- `react-native`, `@react-native/babel-preset`, and `@babel/core`. From Expo SDK 56,
76
- `babel-preset-expo` no longer depends on `@react-native/babel-preset`, and the engine compiles
77
- with Expo's own preset instead, as Metro does. Add
78
- `@testing-library/react-native` if you don't have it yet (the examples below use it):
79
-
80
- ```bash
81
- npm install -D @testing-library/react-native
59
+ npm install -D vitest vite vitest-native @testing-library/react-native
82
60
  ```
83
61
 
84
- See [Requirements](#requirements) for exact versions.
85
-
86
- ---
87
-
88
- ## Quick Start
89
-
90
- Create or update your `vitest.config.ts`:
62
+ `vitest` and `vite` are peer dependencies, and `@testing-library/react-native` is optional. React
63
+ Native and Expo apps already have the Babel packages the default engine uses.
64
+ `npx vitest-native init` writes this config (as `vitest.config.mts` in a TypeScript project), or add it yourself:
91
65
 
66
+ <!-- doc-snippet: vitest.config.mts -->
92
67
  ```ts
68
+ // vitest.config.mts
93
69
  import { defineConfig } from "vitest/config";
94
70
  import { reactNative } from "vitest-native";
95
71
 
@@ -98,922 +74,79 @@ export default defineConfig({
98
74
  });
99
75
  ```
100
76
 
101
- That is it. Write a test:
77
+ Write a test:
102
78
 
79
+ <!-- doc-snippet: src/readme-greeting.test.tsx -->
103
80
  ```tsx
104
- import { test, expect } from "vitest";
81
+ // Greeting.test.tsx
82
+ import { expect, test } from "vitest";
105
83
  import { render, screen } from "@testing-library/react-native";
106
- import { View, Text } from "react-native";
107
-
108
- function Greeting({ name }: { name: string }) {
109
- return (
110
- <View>
111
- <Text>Hello, {name}</Text>
112
- </View>
113
- );
114
- }
84
+ import { Text } from "react-native";
115
85
 
116
86
  test("renders a greeting", async () => {
117
- await render(<Greeting name="World" />);
87
+ await render(<Text>Hello, World</Text>);
118
88
  expect(screen.getByText("Hello, World")).toBeTruthy();
119
89
  });
120
90
  ```
121
91
 
122
- > Prefer Jest-style globals (`test`/`expect` without imports)? Set
123
- > `test: { globals: true }` in your Vitest config. vitest-native does not enable the full
124
- > globals mode; it only exposes `expect` when RNTL needs it to register matchers.
125
- > Awaiting `render` works with RNTL 12–13 and is required by RNTL 14.
126
-
127
- Run it:
128
-
129
- ```bash
130
- npx vitest
131
- ```
132
-
133
- ---
134
-
135
- ## Plugin Options
136
-
137
- The `reactNative()` function accepts an optional configuration object:
138
-
139
- ```ts
140
- import { defineConfig } from "vitest/config";
141
- import { reactNative } from "vitest-native";
142
-
143
- export default defineConfig({
144
- plugins: [
145
- reactNative({
146
- engine: "auto", // 'auto' | 'mock' | 'native' — auto → native when RN's babel deps are present, else mock
147
- platform: "ios", // 'ios' | 'android' (default: 'ios')
148
- presets: [], // Preset[] -- omit for auto-detect
149
- mocks: {}, // Custom mock overrides for the react-native module
150
- diagnostics: false, // Enable verbose logging
151
- assetExts: [".lottie"], // Additional asset extensions to stub
152
- transform: [], // Extra native-engine packages to Flow/TS transform
153
- hotRuntime: false, // false (default) | 'auto' | true | HotRuntimeOptions
154
- }),
155
- ],
156
- });
157
- ```
158
-
159
- | Option | Type | Default | Description |
160
- | ------------- | ------------------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
161
- | `engine` | `'auto' \| 'mock' \| 'native'` | `'auto'` | How React Native is provided to your tests. `auto` runs real RN (native) when available, else mock. See [`engine`](#engine) below. |
162
- | `platform` | `'ios' \| 'android'` | `'ios'` | Target platform. Controls `Platform.OS`, version defaults, and file extension resolution. |
163
- | `presets` | `Preset[]` | auto-detect | Built-in library presets. When omitted, installed packages are detected automatically. Only built-in presets are supported; for custom module mocking, use `vi.mock()` in a setup file. |
164
- | `mocks` | `Record<string, any>` | `{}` | **`engine: 'mock'` only.** JSON-serializable overrides merged into the `react-native` module mock. Function values are not supported; use `vi.mock()` in a setup file for function-based overrides. |
165
- | `diagnostics` | `boolean` | `false` | Log plugin activity to the console for debugging. |
166
- | `assetExts` | `string[]` | `[]` | Additional file extensions to stub as asset imports (beyond the built-in set). |
167
- | `transform` | `string[]` | `[]` | **`engine: 'native'` only.** Extra `node_modules` packages whose source the native engine should transform (Flow/TS/JSX stripped) as it loads them — for third-party RN libraries that ship untranspiled source (e.g. `react-native-reanimated`). Analogous to Jest's `transformIgnorePatterns` allowlist. |
168
- | `hotRuntime` | `boolean \| 'auto' \| HotRuntimeOptions` | `false` | `engine: 'native'` only. Reuse workers while keeping app/test modules isolated per file. `false` (the default) gives each file a fresh worker; `'auto'` opts in where the run can be bounded and recycled, and keeps per-file isolation otherwise. See [Hot runtime](#hot-runtime). |
169
-
170
- ### Experimental Metro configuration
171
-
172
- Pass `metroConfig: true` to use your project's Metro source-extension order and
173
- asset list in both Vite and Node resolution. This is opt-in while the framework
174
- and package-manager compatibility matrix is being validated:
175
-
176
- ```ts
177
- reactNative({ metroConfig: true });
178
- // Config outside the project root:
179
- reactNative({ metroConfig: { configFile: "../../metro.config.cjs" } });
180
- ```
181
-
182
- Expo's defaults prefer TypeScript over JavaScript when both variants exist;
183
- bare React Native's defaults prefer JavaScript. The profile is evaluated in a
184
- short-lived child using the project's own Metro tooling. Explicit `assetExts`
185
- additions still apply. Metro transforms are not installed: source formats such as
186
- SVG need a corresponding Vitest/Vite transform.
187
-
188
- A custom `resolver.resolveRequest` is code and does not run under Vitest: the
189
- source and asset extensions still apply, and a warning names the gap. Where one of
190
- its redirects matters to tests, reproduce it with `resolve.alias`. Package
191
- main fields and conditions remain governed by the engine's ownership policy;
192
- `diagnostics: true` reports the observed Metro values. Config is evaluated on
193
- startup; changing it requires restarting the run.
194
-
195
- Default: `false`. Findings and remaining gates are recorded in
196
- [the investigation log](docs/metro-profile-investigation.md).
197
-
198
- ### `engine`
199
-
200
- Choose how React Native is provided to your tests:
201
-
202
- - `'native'` — runs the **real** React Native JavaScript (component logic, prop
203
- computation, validation, reconciliation), mocking only the native module boundary that
204
- requires a device. Jest's `react-native` preset replaces many of these modules with
205
- stubs, so the native engine exercises behavior Jest's mocks skip (see [Fidelity](#fidelity)
206
- below). Best for components, integration, RNTL, virtualized lists, and anywhere a false
207
- pass is costly. Requires `@react-native/babel-preset` (or, from Expo SDK 56, Expo's
208
- preset) and `@babel/core`, present by default in React Native and Expo apps.
209
- - `'mock'` — a lightweight, pure-JS reimplementation of React Native with **zero extra
210
- dependencies**. Best for pure-logic/unit tests, maximum determinism, or when you can't
211
- add the babel deps. Like Jest's preset, it is a simplification — see [Fidelity](#fidelity).
212
- - `'auto'` _(default)_ — picks automatically, and **resolves to `'native'`** whenever a React
213
- Native Babel preset and `@babel/core` are present (i.e. in any real RN or Expo app). It
214
- falls back to `'mock'` only when those deps are absent, printing one line to explain why.
215
- So `reactNative()` with no options runs real React Native. Set `engine: 'mock'` to opt out.
216
-
217
- ```ts
218
- reactNative({ engine: "native" });
219
- ```
220
-
221
- On the first cold run, the native engine compiles React Native's synchronous module graph into a
222
- factory registry in a short-lived, heap-bounded child process. The child exits before test workers
223
- start, so Babel's compilation heap does not become a permanent Vite-process RSS watermark. Later
224
- runs validate and reuse the cache in-process without launching the compiler. A failed optimization
225
- remains visible and falls back to the slower per-file loader without changing test results.
226
-
227
- #### Fidelity
228
-
229
- Jest's `react-native` preset replaces many real modules with stubs, so behavior they
230
- don't implement passes silently. The `native` engine runs the real implementations, so
231
- those checks actually run. For example:
232
-
233
- | Behavior | `engine: 'native'` (real RN) | Jest `react-native` preset |
234
- | ---------------------- | ---------------------------------------------------------------------------- | -------------------------- |
235
- | `Linking.openURL(123)` | throws `Invalid URL: should be a string` | accepts without validating |
236
- | `Linking.openURL('')` | throws `Invalid URL: cannot be empty` | accepts without validating |
237
- | `<Text>` host props | `accessible`, `allowFontScaling`, `ellipsizeMode` computed by real `Text.js` | not set |
238
-
239
- The `mock` engine is a simplification too, so it diverges from real RN the same way — reach
240
- for `native` when a false pass would be costly. These specific differences are produced by
241
- the cross-check/fidelity harnesses in the repository's `bench/` directory.
242
-
243
- #### Hot runtime
244
-
245
- Vitest's default isolation gives each test file a fresh worker, so React Native reloads for every
246
- file; that is the default (`hotRuntime: false`), as in 0.13.0. With `hotRuntime: 'auto'` the native
247
- engine instead reuses workers and resets modules per file whenever that can be done safely. It has
248
- known differences from per-file isolation, listed under "A test passes on its own but fails when
249
- run with other files" in the troubleshooting guide.
250
-
251
- `'auto'` selects persistent workers when the current scheduler provides recyclable task boundaries,
252
- the host/container memory plan admits at least two workers, no other pool was explicitly
253
- selected, and `test.isolate` is not set explicitly — an explicit Vitest isolation choice, `true` or
254
- `false`, is always kept. The same holds for CLI flags (`--pool`, `--isolate`, `--no-isolate`,
255
- `--maxWorkers=1`, `--no-file-parallelism`). With `hotRuntime: true` instead, any of these fails at
256
- startup with `HOT_RUNTIME_OVERRIDDEN` rather than being overridden. `'auto'` also keeps Vitest's
257
- isolation when another project in the same `sequence.groupOrder` runs a different worker count,
258
- which Vitest does not allow; give the native project its own `test.sequence.groupOrder` to keep hot.
259
- Suites migrated from Jest (`jestMockTransform()`, the jest-compat setup) are included: the
260
- jest-compat surface — `jest.mock` in its forms, runtime mocks, spies, timers, React Native Testing
261
- Library cleanup — has its own cross-file isolation gate under the hot runtime. The decision runs
262
- after other Vite config hooks, so a pool contributed by a later plugin is included rather than
263
- producing a mixed runtime. When it falls
264
- back to per-file isolation it prints the reason. Per-file isolation, the default, can also be set
265
- explicitly:
266
-
267
- ```ts
268
- reactNative({
269
- engine: "native",
270
- hotRuntime: false,
271
- });
272
- ```
273
-
274
- To require hot mode and fail closed when it cannot be bounded, use the explicit form:
275
-
276
- ```ts
277
- reactNative({
278
- engine: "native",
279
- hotRuntime: true,
280
- });
281
- ```
282
-
283
- The hot runtime keeps React Native's precompiled factory registry and worker realm warm while
284
- resetting the registry's module instances and the app/test module graph for every file. An ordered
285
- state manifest also restores and verifies timers/Vitest stubs, direct `process.env` changes,
286
- process and RN listeners, complete global and console property descriptors, known RN state,
287
- ErrorUtils, Expo runtime state, and plugin boundary mocks. A mutation gate removes each of its
288
- eleven restore actions in turn and requires the cross-file isolation suite to fail by name.
289
-
290
- When hot is enabled, the plugin derives a worker-total memory plan from the lower of host and
291
- container/cgroup memory. It reserves main-process and replacement headroom, caps automatic
292
- concurrency at four, recycles workers on local heap or process RSS, and stops before starting more
293
- work at the hard RSS boundary. Run with `diagnostics: true` or `vitest-native doctor` to see the
294
- chosen envelope.
295
-
296
- **Known limitation.** No shared-realm sanitizer can generically discover arbitrary mutable state in
297
- every resident third-party singleton. The registry resets React Native's own in-memory module
298
- instances, and the manifest handles the supported runtime surfaces above; unknown process-wide
299
- state is still the library's or test fixture's responsibility. A test that passes alone but fails
300
- after another file is a correctness signal: set `hotRuntime: false` for that suite and report the
301
- small reproduction. The hot runtime depends on Vitest's custom worker APIs, which Vitest labels
302
- experimental.
303
-
304
- For additional leak containment:
305
-
306
- ```ts
307
- reactNative({
308
- engine: "native",
309
- hotRuntime: {
310
- recycleAfterFiles: 100,
311
- memoryLimit: 512 * 1024 * 1024,
312
- preserveGlobals: ["MY_RESIDENT_LIBRARY_REGISTRY"],
313
- },
314
- });
315
- ```
316
-
317
- Recycling is applied between Vitest scheduler tasks. Current Vitest batches every file into one
318
- uninterruptible task at `maxWorkers: 1`, so the default `'auto'` keeps per-file isolation there and
319
- `hotRuntime: true` fails that configuration rather than claim an inert memory bound. Use at least
320
- two workers for hot mode. If an external scheduler
321
- already provides a hard boundary, you can deliberately accept the risk with
322
- `hotRuntime: { allowUnboundedMemory: true }`; this disables the automatic worker cap and
323
- process-RSS enforcement and prints a warning when the batch is observed. `preserveGlobals` is an
324
- exact allowlist for registries created by resident external dependencies; Storybook's preview
325
- registry is preserved automatically.
326
-
327
- This mode uses Vitest's custom pool and worker APIs, so it remains experimental. CI runs the
328
- complete native suite under both the lockfile Vitest and the newest supported Vitest release,
329
- plus a generated 100-file isolation soak, an end-to-end memory-triggered recycling test, and a
330
- packed auto-selection matrix covering enablement and every guarded fallback class.
331
-
332
- ---
333
-
334
- ## Mocked Components and APIs
335
-
336
- Under the `mock` engine, the plugin provides a comprehensive mock of the `react-native` module. Every mocked component renders as a named host element (making snapshots readable), and every mocked API function is a Vitest `vi.fn()` spy.
337
-
338
- ### Components (24)
339
-
340
- | Component | Component | Component |
341
- | ----------------------- | -------------------- | ------------------------ |
342
- | View | Text | Image |
343
- | TextInput | ScrollView | FlatList |
344
- | SectionList | Modal | Pressable |
345
- | TouchableOpacity | TouchableHighlight | TouchableWithoutFeedback |
346
- | TouchableNativeFeedback | ActivityIndicator | Button |
347
- | Switch | RefreshControl | StatusBar |
348
- | SafeAreaView | KeyboardAvoidingView | ImageBackground |
349
- | VirtualizedList | InputAccessoryView | DrawerLayoutAndroid |
350
-
351
- ### APIs (25+)
352
-
353
- | API | API | API |
354
- | ------------------ | ------------------ | ------------------ |
355
- | Platform | Dimensions | StyleSheet |
356
- | Animated | Alert | Linking |
357
- | AppState | Keyboard | BackHandler |
358
- | Vibration | PermissionsAndroid | Appearance |
359
- | PixelRatio | LayoutAnimation | Clipboard |
360
- | Share | AccessibilityInfo | InteractionManager |
361
- | PanResponder | ToastAndroid | ActionSheetIOS |
362
- | LogBox | Easing | I18nManager |
363
- | DeviceEventEmitter | | |
364
-
365
- ### Native Bridge
366
-
367
- | Export | Description |
368
- | ------------------------ | -------------------------------------------- |
369
- | `NativeModules` | Proxy that returns no-op modules for any key |
370
- | `TurboModuleRegistry` | Proxy with `getEnforcing` / `get` stubs |
371
- | `UIManager` | Stubbed layout manager |
372
- | `NativeEventEmitter` | Event emitter constructor mock |
373
- | `requireNativeComponent` | Returns a named component mock |
374
-
375
- ### Hooks
376
-
377
- | Hook | Default Value |
378
- | --------------------- | ----------------------------------------------------- |
379
- | `useColorScheme` | `'light'` |
380
- | `useWindowDimensions` | `{ width: 390, height: 844, scale: 3, fontScale: 1 }` |
381
-
382
- ---
383
-
384
- ## React Native Test Suite Conformance
385
-
386
- vitest-native ports tests from React Native's own test suite (Flow stripped, Jest → Vitest) to validate mock behavioral parity — the same checks Meta uses to verify React Native itself:
387
-
388
- - **Easing** — all 24 easing curve tests including sample data for quad, cubic, sin, exp, circle, and back
389
- - **Bezier** — 9 cubic bezier mathematical property tests (symmetry, projection, boundary conditions)
390
- - **flattenStyle** — 12 style merging tests covering override precedence, reference identity, and recursive flattening
391
- - **processColor** — 9 color format conversion tests for named colors, RGB, RGBA, HSL, HSLA, and hex
392
- - **Interpolation** — 12 numeric and string range mapping tests, including string output ranges (`deg`/`%`/arbitrary suffixes) and extrapolate modes (extend/clamp/identity)
393
- - **Animated** — 36 tests for listeners, events, forkEvent, diffClamp, Color normalization, sequence chaining/interruption/restart, parallel start/stop/no-double-stop, loop iterations/indefinite/interrupt/resetBeforeIteration, delay in sequence, stagger, and value tracking
394
-
395
- 118 tests ported from React Native's own test suite — 115 passing, with 3 edge cases (hex-colour interpolation and infinite input ranges) skipped and documented in the test files (`vitest run tests/rn-conformance/`).
396
-
397
- ---
398
-
399
- ## Test Helpers
400
-
401
- Import helpers from `vitest-native/helpers` to control test state. `setDimensions`,
402
- `setColorScheme`, `setInsets`, `mockNativeModule`, and `resetAllMocks` work under both engines.
403
- `setPlatform` is mock-engine-only because the native engine selects platform files while loading
404
- the module graph.
405
-
406
- ```ts
407
- import {
408
- setPlatform,
409
- setDimensions,
410
- setColorScheme,
411
- setInsets,
412
- mockNativeModule,
413
- resetAllMocks,
414
- } from "vitest-native/helpers";
415
- ```
416
-
417
- ### `setPlatform(os)`
418
-
419
- Switch the platform for the current test under `engine: 'mock'`. Updates `Platform.OS`,
420
- `Platform.Version`, and `Platform.select`.
421
-
422
- ```ts
423
- import { setPlatform } from "vitest-native/helpers";
424
-
425
- test("renders Android-specific UI", () => {
426
- setPlatform("android");
427
- // Platform.OS is now 'android', Platform.Version is 34
428
- // Platform.select({ ios: 'A', android: 'B' }) returns 'B'
429
- });
430
- ```
431
-
432
- Under `engine: 'native'`, configure `reactNative({ platform: 'android' })` or use separate Vitest
433
- projects. Calling `setPlatform()` there throws because changing `Platform.OS` after platform-specific
434
- modules have resolved would create an inconsistent graph.
435
-
436
- ### `setDimensions(dims)`
437
-
438
- Update `Dimensions.get()` and the `useWindowDimensions` hook return value.
439
-
440
- ```ts
441
- import { setDimensions } from "vitest-native/helpers";
442
-
443
- test("adapts to tablet dimensions", () => {
444
- setDimensions({ width: 768, height: 1024, scale: 2, fontScale: 1 });
445
- // Dimensions.get('window') returns { width: 768, height: 1024, ... }
446
- // useWindowDimensions() returns the same
447
- });
448
- ```
449
-
450
- ### `setColorScheme(scheme)`
451
-
452
- Switch the color scheme. Affects `Appearance.getColorScheme()` and the `useColorScheme` hook.
453
-
454
- ```ts
455
- import { setColorScheme } from "vitest-native/helpers";
456
-
457
- test("renders dark mode styles", () => {
458
- setColorScheme("dark");
459
- // useColorScheme() returns 'dark'
460
- // Appearance.getColorScheme() returns 'dark'
461
- });
462
- ```
463
-
464
- ### `setInsets(insets)`
465
-
466
- Update the safe area insets returned by `useSafeAreaInsets()` from `react-native-safe-area-context`. Requires the `safeAreaContext` preset to be active.
467
-
468
- ```ts
469
- import { setInsets } from "vitest-native/helpers";
470
-
471
- test("renders with no bottom inset (Android)", () => {
472
- setInsets({ top: 24, bottom: 0 });
473
- // useSafeAreaInsets() returns { top: 24, right: 0, bottom: 0, left: 0 }
474
- });
475
- ```
476
-
477
- ### `mockNativeModule(name, impl)`
478
-
479
- Register a custom native module mock. The module becomes available through both
480
- `NativeModules[name]` and `TurboModuleRegistry.get(name)`.
481
-
482
- ```ts
483
- import { mockNativeModule } from "vitest-native/helpers";
484
-
485
- test("uses a custom native module", () => {
486
- mockNativeModule("MyBridge", {
487
- getValue: vi.fn().mockResolvedValue(42),
488
- });
489
-
490
- const { NativeModules } = require("react-native");
491
- await expect(NativeModules.MyBridge.getValue()).resolves.toBe(42);
492
- });
493
- ```
494
-
495
- ### `resetAllMocks()`
496
-
497
- Reset plugin-controlled state. Under the mock engine this restores the mock defaults, including
498
- iOS platform defaults. Under the native engine it restores the configured platform's initial
499
- dimensions and color scheme. Both engines reset active preset stores, clear mock call history, and
500
- undo `mockNativeModule` calls.
501
-
502
- ```ts
503
- import { resetAllMocks } from "vitest-native/helpers";
504
-
505
- afterEach(() => {
506
- resetAllMocks();
507
- });
508
- ```
509
-
510
- ---
511
-
512
- ## Auto-Detect Presets
513
-
514
- When the `presets` option is omitted, the plugin scans your `node_modules` and automatically enables mocks for installed third-party libraries:
515
-
516
- | Package | What Gets Mocked |
517
- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
518
- | `react-native-reanimated` | Animated values, `useSharedValue`, `useAnimatedStyle`, layout animations |
519
- | `react-native-gesture-handler` | Gesture components, `GestureHandlerRootView`, state constants |
520
- | `react-native-safe-area-context` | `SafeAreaProvider`, `useSafeAreaInsets`, `SafeAreaView` |
521
- | `@react-navigation/native` | `NavigationContainer`, `useNavigation`, `useRoute` |
522
- | `@react-native-async-storage/async-storage` | `getItem`, `setItem`, `removeItem`, `clear`, `getAllKeys` |
523
- | `react-native-screens` | `enableScreens`, screen components |
524
- | `expo` | `expo-constants`, `expo-font`, `expo-asset`, `expo-splash-screen`, `expo-linking`, `expo-status-bar` |
525
-
526
- Auto-detection means zero additional config for most projects. If you need to restrict which presets are active, pass them explicitly:
527
-
528
- ```ts
529
- import { defineConfig } from "vitest/config";
530
- import { reactNative, presets } from "vitest-native";
92
+ Run it with `npx vitest`, or add `"test": "vitest"` to your scripts. If something looks off,
93
+ `npx vitest-native doctor` checks your versions, engine and presets.
531
94
 
532
- export default defineConfig({
533
- plugins: [
534
- reactNative({
535
- presets: [presets.reanimated(), presets.gestureHandler(), presets.safeAreaContext()],
536
- }),
537
- ],
538
- });
539
- ```
95
+ ## Coming from Jest or jest-expo
540
96
 
541
- ### Available Presets
542
-
543
- | Preset | Library | What's mocked |
544
- |--------|---------|---------------|
545
- | `presets.reanimated()` | `react-native-reanimated` | `useSharedValue`, `useAnimatedStyle`, `withTiming`, `withSpring`, `withDelay`, `withSequence`, `withRepeat`, layout animations (`FadeIn`, `FadeOut`, `SlideInRight`), `Easing`, `interpolate`, `createAnimatedComponent` |
546
- | `presets.worklets()` | `react-native-worklets` | `runOnJS`, `runOnUI`, `scheduleOnRN`, `scheduleOnUI`, `createWorkletRuntime`, … run synchronously on the JS thread |
547
- | `presets.gestureHandler()` | `react-native-gesture-handler` | `GestureHandlerRootView`, gesture handlers (Pan, Tap, LongPress, Pinch, Rotation, Fling), `Gesture` API (v2), `GestureDetector`, `Swipeable`, touchable wrappers, state constants |
548
- | `presets.safeAreaContext()` | `react-native-safe-area-context` | `SafeAreaProvider`, `SafeAreaView`, `useSafeAreaInsets`, `useSafeAreaFrame`, `initialWindowMetrics`, `withSafeAreaInsets` |
549
- | `presets.navigation()` | `@react-navigation/native`, `@react-navigation/native-stack`, `@react-navigation/bottom-tabs`, `@react-navigation/drawer`, `@react-navigation/elements` | `NavigationContainer`, `useNavigation`, `useRoute`, `useFocusEffect`, `useIsFocused`, `CommonActions`, `StackActions`, `TabActions`, `DrawerActions`, navigators |
550
- | `presets.screens()` | `react-native-screens` | `enableScreens`, `Screen`, `ScreenContainer`, `ScreenStack` |
551
- | `presets.asyncStorage()` | `@react-native-async-storage/async-storage` | in-memory store (`getItem`/`setItem`/`multiGet`/`mergeItem`/…) |
552
- | `presets.expo()` | `expo-constants`, `expo-font`, `expo-asset`, `expo-splash-screen`, `expo-linking`, `expo-status-bar` | constants, fonts, assets, splash screen, linking, status bar |
553
- | `presets.deviceInfo()` | `react-native-device-info` | string/bool/number getters with sync + async variants |
554
- | `presets.mmkv()` | `react-native-mmkv` | in-memory `MMKV` + `useMMKV*` hooks, for mmkv 2 only: the library tests itself from v3 (its own in-memory backend under Vitest), so the preset steps aside |
555
- | `presets.netInfo()` | `@react-native-community/netinfo` | connected-wifi state, `fetch`/`refresh`/`addEventListener`/`useNetInfo`, state-type enums |
556
- | `presets.svg()` | `react-native-svg` | `Svg`, `Path`, `Circle`, `Rect`, `G`, … as host components |
557
- | `presets.webview()` | `react-native-webview` | `WebView` (default + named) host component |
558
- | `presets.vectorIcons()` | `@react-native-vector-icons/common` | `createIconSet` and the dynamic font loader shared by the v10+ scoped icon sets (not the legacy unscoped `react-native-vector-icons`) |
559
- | `presets.flashList()` | `@shopify/flash-list` | `FlashList` rendering its data through `renderItem`, the ref surface, v2 recycler hooks |
560
- | `presets.bottomSheet()` | `@gorhom/bottom-sheet` | `BottomSheet`, `BottomSheetModal` + provider, sheet views, scroll/list variants, `BottomSheetTextInput`, backdrop, footer |
561
- | `presets.keyboardController()` | `react-native-keyboard-controller` | `KeyboardProvider`, `KeyboardAvoidingView`, `KeyboardAwareScrollView`, `KeyboardStickyView`, `KeyboardToolbar`; the imperative `KeyboardController` is inert |
562
- | `presets.unistyles()` | `react-native-unistyles`, `react-native-unistyles/reanimated` | Unistyles 3: `StyleSheet.configure`/`create` with themes, variants and compound variants, `useUnistyles`, `withUnistyles`, `UnistylesRuntime` theme switching, `mq` with `Display`/`Hide`; matches the library's own Jest mock and follows its source where that mock does less |
563
- | `presets.skia()` | `react-native-skia`, `@shopify/react-native-skia` | Skia's own test mock (`Mock(CanvasKit)`) over CanvasKit, Skia compiled to WebAssembly: the `Skia` API computes with real Skia, `Canvas` and its drawing render as Views; plus Skia's Reanimated helpers (`usePathValue`, `useTexture`, …) and a `matchFont` that returns a font |
564
-
565
- Presets apply under **both** engines: the mock engine and `engine: 'native'` (where they shadow each
566
- library's native runtime — worklets, native modules — exactly as Jest does, while the surrounding tree
567
- renders through real React Native).
568
-
569
- ### Expo
570
-
571
- Expo apps need no Expo-specific package. Under the native engine every Expo package's own
572
- JavaScript runs for real — `expo` itself, expo-router, React Navigation and Expo modules such as
573
- `expo-constants` or `expo-splash-screen` — and only their native modules are mocked, the way
574
- `jest-expo` runs them. (The mock engine replaces the common Expo modules with the `expo` preset.)
575
-
576
- - **Coming from jest-expo:** `npx vitest-native migrate --write` translates the `jest-expo`
577
- presets (`jest-expo/android` → `platform: 'android'`) and, because jest-expo does not mock React
578
- Navigation, turns the navigation preset off when a `@react-navigation/*` package is installed.
579
- - **expo-router screens:** `expo-router/testing-library` (`renderRouter`, `testRouter`,
580
- `toHavePathname`) runs as written with the jest-compat layer. From SDK 57 expo-router bundles its
581
- own React Navigation; before SDK 57, also set `presets: { navigation: false }`.
582
- - **Expo modules** run their real JavaScript, and their native modules answer as under
583
- jest-expo: from the package's own `mocks/<Name>.ts` where it ships one, else from Expo's table
584
- of the native modules (`Device.modelName` is `'mock'`). An optional native module a package
585
- probes for, and that no installed package defines, is absent, as on a device.
586
- - **Expo SDK trails React Native.** Pin your `react-native` to the version your Expo SDK supports
587
- (SDK 54 and later are within this plugin's validated range), not the newest RN release.
588
-
589
- Packed Expo SDK 58 and SDK 57 apps are installed from the release tarball and tested in CI: Expo
590
- module auto-detection and rendering, and expo-router's testing library against file-based `app/`
591
- routes. The SDK 58 app also runs those routes under the configuration `migrate` generates from a
592
- jest-expo setup. See the
97
+ `npx vitest-native migrate` reads your Jest config and reports what maps over; `--write` saves the
98
+ suggested Vitest config. Existing `jest.fn`, `jest.mock` and `jest.useFakeTimers` calls keep working
99
+ through the jest-compat layer. See [migrating from Jest](https://danfry1.github.io/vitest-native/migration/from-jest) and the
593
100
  [Expo guide](https://danfry1.github.io/vitest-native/guide/expo).
594
101
 
595
- ---
596
-
597
- ## Migrating from `vitest-react-native`
598
-
599
- Used [`vitest-community/vitest-react-native`](https://github.com/vitest-community/vitest-react-native)
600
- and it broke on a newer Vitest? `vitest-native` is the maintained continuation — same core
601
- architecture (externalize RN, run its real JS under Node, mock only the native boundary). For the
602
- common case it's a config swap:
603
-
604
- ```diff
605
- - import reactNative from 'vitest-react-native';
606
- - import react from '@vitejs/plugin-react';
607
- + import { reactNative } from 'vitest-native';
608
- import { defineConfig } from 'vitest/config';
609
-
610
- export default defineConfig({
611
- - plugins: [reactNative(), react()],
612
- + plugins: [reactNative()],
613
- });
614
- ```
615
-
616
- Named import, and drop `@vitejs/plugin-react` (vitest-native handles the JSX runtime itself). The
617
- full walkthrough — install, gotchas, what's the same — is in
618
- **[docs/migrating-from-vitest-react-native.md](docs/migrating-from-vitest-react-native.md)**.
619
-
620
- ---
621
-
622
- ## Migrating from Jest
623
-
624
- vitest-native ships a small compat layer that clears the mechanical Jest-API coupling in an existing
625
- suite (the `jest` global, `@jest/globals`, jest-native's extend-expect):
102
+ ## Requirements
626
103
 
627
- ```ts
628
- // vitest.config.mts
629
- import { reactNative } from "vitest-native";
630
- import { jestCompatAliases, jestCompatSetup } from "vitest-native/jest-compat";
104
+ | | Supported |
105
+ |---|---|
106
+ | Node.js | 22.13+ on Node 22, or 24.3+ |
107
+ | Vitest | 4.x or 5.x |
108
+ | Vite | ^6.4.2, ^7.3.2 or ^8.0.5 |
109
+ | React | 18 or later |
110
+ | React Native | 0.81–0.88 |
111
+ | Expo SDK | 57 and 58 |
112
+ | React Native Testing Library | 12.x, 13.x or 14.x (optional) |
631
113
 
632
- export default defineConfig({
633
- plugins: [reactNative({ engine: "native" })],
634
- resolve: { alias: { ...jestCompatAliases() } },
635
- test: { globals: true, setupFiles: [jestCompatSetup] },
636
- });
637
- ```
114
+ Use the React version your React Native release requires, and a `@react-native/babel-preset`
115
+ that matches its minor version. Node 24.0–24.2 are excluded because `jest.mock` does not reach
116
+ modules Node loads there.
638
117
 
639
- This is **not** a turnkey drop-in — a real suite still needs a small per-suite cleanup (convert
640
- top-level `jest.mock` → `vi.mock`, RNTL ≥ 12, re-record snapshots once with `-u`). The full recipe,
641
- with a worked real-app example, is in **[docs/migrating-from-jest.md](docs/migrating-from-jest.md)**.
118
+ ## Learn more
642
119
 
643
- ---
120
+ - [Choosing an engine](https://danfry1.github.io/vitest-native/guide/engines) and the [hot runtime](https://danfry1.github.io/vitest-native/guide/engines#hot-runtime)
121
+ - [Third-party presets](https://danfry1.github.io/vitest-native/guide/presets) (Reanimated, Gesture Handler, Navigation, …)
122
+ - [Expo](https://danfry1.github.io/vitest-native/guide/expo) · [Plugin options](https://danfry1.github.io/vitest-native/guide/plugin-options) · [Test helpers](https://danfry1.github.io/vitest-native/guide/helpers)
123
+ - [Coverage](https://danfry1.github.io/vitest-native/guide/coverage) · [CLI](https://danfry1.github.io/vitest-native/guide/cli) · [Troubleshooting](https://danfry1.github.io/vitest-native/guide/troubleshooting)
124
+ - [Release notes for 0.14](https://danfry1.github.io/vitest-native/releases/0.14) · [Changelog](https://github.com/danfry1/vitest-native/blob/main/packages/vitest-native/CHANGELOG.md)
644
125
 
645
- ## Troubleshooting
126
+ ## Status
646
127
 
647
- **`npm error Cannot read properties of null (reading 'edgesOut')` during install**
648
- npm 10 (the version bundled with Node 22) crashes while resolving Vite 8.2+'s optional peer
649
- chain when the project pins Vitest 4, because that chain resolves to the latest Vitest (5.x).
650
- This is an npm bug, fixed in npm 11 ([vitest#11245](https://github.com/vitest-dev/vitest/issues/11245)).
651
- Upgrade npm (`npm install --global npm@11`), or use pnpm, Yarn or Bun.
128
+ Beta. What is covered by semver, what is experimental and what 1.0 will mean are set out in
129
+ [versioning and stability](https://github.com/danfry1/vitest-native/blob/main/packages/vitest-native/docs/versioning.md).
130
+ vitest-native is the maintained successor to
131
+ [`vitest-community/vitest-react-native`](https://github.com/vitest-community/vitest-react-native),
132
+ rebuilt for Vitest 4 and 5; see [migrating from it](https://danfry1.github.io/vitest-native/migration/from-vitest-react-native).
652
133
 
653
- **`@react-native/babel-preset not found — using the mock engine`**
654
- You asked for the default (`auto`) engine but the native babel deps aren't installed, so it
655
- fell back to the mock engine. An Expo project from SDK 56 needs nothing extra: the engine uses
656
- Expo's preset, and `expo` brings `@babel/core`. Otherwise, to run real React Native, install them:
134
+ ## Contributing
657
135
 
658
136
  ```bash
659
- npm i -D @react-native/babel-preset @babel/core
660
- ```
661
-
662
- To silence the notice and stay on mock deliberately, set `reactNative({ engine: 'mock' })`.
663
-
664
- **`vi.mock('some-rn-library')` doesn't take effect (native engine)**
665
- Under `engine: 'native'`, React Native and its native-side libraries are _externalized_ to Node,
666
- so they load outside Vite's module graph — and Vitest's mocker only intercepts modules inside that
667
- graph. Your **own** source modules mock normally; the gap is third-party RN-side packages. Options:
668
-
669
- - Use a **[preset](#auto-detect-presets)** if one exists (it shadows the library the way Jest does).
670
- - For a pure-JS library shipping untranspiled source, add it to the [`transform`](#plugin-options)
671
- allowlist so the engine strips its Flow/TS as it loads.
672
- - Or test that boundary on the **mock engine**, where `vi.mock` applies normally.
673
-
674
- **`Unexpected token` / Flow syntax errors from a third-party library (native engine)**
675
- The require hook strips Flow/TS from `react-native` and active presets, but not from arbitrary
676
- packages. If a dependency ships untranspiled Flow/TS, add it to the
677
- [`transform`](#plugin-options) allowlist.
678
-
679
- **My `babel.config.js` plugin isn't running**
680
- Transforms go through Vite's JSX transformer, not your Babel config, so custom Babel plugins don't
681
- apply. Vite 6–7 use esbuild and Vite 8 uses Oxc; the plugin configures the automatic JSX runtime for
682
- both. RN/preset Flow-stripping is handled separately; for anything else, prefer a Vite plugin or a
683
- preset.
684
-
685
- **Snapshots differ after switching from Jest or the mock engine**
686
- Real RN computes host props (e.g. `<Text>`'s `accessible`, `allowFontScaling`) that mocks omit, so
687
- the tree is richer. Re-record once with `npx vitest -u` after migrating.
688
-
689
- **`Worker terminated due to reaching memory limit` / `JS heap out of memory` (large native suites)**
690
- Every test file that renders real React Native loads a full renderer, so a large suite can grow a
691
- worker's heap past Node's default ceiling. Cap it with Vitest's per-worker limit — Vitest recycles a
692
- worker once its heap exceeds the limit, so growth never reaches the hard OOM:
693
-
694
- ```ts
695
- // vitest.config.ts
696
- export default defineConfig({
697
- test: { poolOptions: { threads: { memoryLimit: "512MB" } } },
698
- });
137
+ bun install
138
+ bun run --filter vitest-native build
139
+ bun run --filter vitest-native test
699
140
  ```
700
141
 
701
- The hot runtime (the default where it can be bounded) also helps: it keeps React Native's precompiled
702
- factory registry warm, resets its module instances from memory per file, and recycles workers on a
703
- memory/file budget.
704
-
705
- **`Vitest caught N unhandled errors` in error-boundary tests**
706
- A test that intentionally throws inside a component (to exercise an error boundary) makes React log
707
- a "recovered from an error during concurrent rendering" message and Vitest count it — even though
708
- the boundary worked and the test passes. It's cosmetic and the assertions are unaffected. Silence it
709
- in a setup file if you like (e.g. filter the message in an `onConsoleLog`/`console.error` wrapper).
710
-
711
- **Overriding a preset's mock (e.g. navigation route params)**
712
- Auto-detected presets shadow a library with a built-in mock. To change what that mock returns for a
713
- test or project, `vi.mock` the module in a setup file and spread the preset's mock — presets expose
714
- the module to Vitest's graph, so `vi.mock` applies and `importOriginal()` returns the preset mock:
715
-
716
- ```ts
717
- // vitest.setup.ts
718
- vi.mock("@react-navigation/native", async (importOriginal) => ({
719
- ...(await importOriginal()),
720
- useRoute: () => ({ key: "r", name: "Screen", params: { id: "1" } }),
721
- }));
722
- ```
723
-
724
- ---
725
-
726
- ## RNTL Matchers
727
-
728
- When supported `@testing-library/react-native` 12–14 is installed, `vitest-native`
729
- auto-registers its custom matchers across each major's export layout. No manual
730
- `extend(matchers)` call or setup file is needed.
731
-
732
- ### TypeScript
733
-
734
- The matchers run without any setup, but their **types** need one line. RNTL declares
735
- them only for Jest — it augments the global `jest` namespace and `@jest/expect`, and
736
- neither reaches Vitest's `Assertion` — so without this they are
737
- `Property 'toHaveTextContent' does not exist on type 'Assertion<...>'` even though the
738
- assertion works at runtime.
739
-
740
- Reference the types once, anywhere in the project:
741
-
742
- ```ts
743
- /// <reference types="vitest-native/rntl-matchers" />
744
- ```
745
-
746
- or add it to `compilerOptions.types` in `tsconfig.json`:
747
-
748
- ```json
749
- { "compilerOptions": { "types": ["vitest-native/rntl-matchers"] } }
750
- ```
751
-
752
- It is opt-in rather than automatic because `@testing-library/react-native` is an
753
- optional peer: a type import of an absent package is invisible under
754
- `skipLibCheck: true` (React Native's default) but reports `TS2307` under
755
- `skipLibCheck: false`, which would break projects that use the mock engine without
756
- RNTL. Referencing nothing loads nothing — the file is not part of the program unless
757
- asked for.
758
-
759
- The following matchers become available on `expect()`:
760
-
761
- | Matcher | Description |
762
- | --------------------------------- | --------------------------------------------- |
763
- | `toBeVisible()` | Element is visible |
764
- | `toBeEmptyElement()` | Element has no children |
765
- | `toBeEnabled()` | Element is not disabled |
766
- | `toBeDisabled()` | Element is disabled |
767
- | `toHaveTextContent(text)` | Element contains the given text |
768
- | `toHaveProp(name, value?)` | Element has the specified prop |
769
- | `toHaveStyle(style)` | Element has the specified styles |
770
- | `toBeOnTheScreen()` | Element is in the component tree |
771
- | `toContainElement(element)` | Element contains the given child |
772
- | `toHaveAccessibilityState(state)` | Element has the specified accessibility state |
773
- | `toHaveAccessibilityValue(value)` | Element has the specified accessibility value |
774
- | `toBeSelected()` | Element is selected |
775
- | `toBeChecked()` | Element is checked |
776
- | `toBePartiallyChecked()` | Element is partially checked |
777
- | `toBeBusy()` | Element is busy |
778
- | `toBeExpanded()` | Element is expanded |
779
- | `toBeCollapsed()` | Element is collapsed |
780
-
781
- ```tsx
782
- import { render, screen } from "@testing-library/react-native";
783
- import { View, Text } from "react-native";
784
-
785
- test("greeting is visible with correct style", async () => {
786
- await render(
787
- <View>
788
- <Text style={{ color: "red", fontSize: 18 }}>Hello</Text>
789
- </View>,
790
- );
791
-
792
- const text = screen.getByText("Hello");
793
- expect(text).toBeVisible();
794
- expect(text).toHaveStyle({ color: "red" });
795
- expect(text).toHaveTextContent("Hello");
796
- });
797
- ```
798
-
799
- ---
800
-
801
- ## Animated Matchers (Reanimated)
802
-
803
- `react-native-reanimated` ships `toHaveAnimatedStyle` and `toHaveAnimatedProps` through its Jest setup, which isn't available under Vitest. `vitest-native` registers Vitest-native equivalents automatically — no `setUpTests()` call or setup file needed.
804
-
805
- | Matcher | Description |
806
- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
807
- | `toHaveAnimatedStyle(style, config?)` | Element's (flattened) style contains the given entries. Pass `{ shouldMatchAllProps: true }` to require an exact match. |
808
- | `toHaveAnimatedProps(props)` | Element's animated props contain the given entries. |
809
-
810
- Because the `reanimated` preset resolves `useAnimatedStyle`/`useAnimatedProps` synchronously, the animated values land on the rendered element and these matchers read straight from it:
811
-
812
- ```tsx
813
- import { render, screen } from "@testing-library/react-native";
814
- import Animated, { useSharedValue, useAnimatedStyle } from "react-native-reanimated";
815
-
816
- function Skeleton({ visible }: { visible: boolean }) {
817
- const opacity = useSharedValue(visible ? 1 : 0);
818
- const style = useAnimatedStyle(() => ({ opacity: opacity.value }));
819
- return <Animated.View testID="bone" style={style} />;
820
- }
142
+ ## Contributors
821
143
 
822
- test("starts with full opacity", async () => {
823
- await render(<Skeleton visible />);
824
- expect(screen.getByTestId("bone")).toHaveAnimatedStyle({ opacity: 1 });
825
- });
826
- ```
827
-
828
- ### Reanimated + Gesture Handler without manual mocks
829
-
830
- Both libraries are auto-detected, so a component using a `Gesture` + `GestureDetector` driving an animated style needs no `vi.mock()` calls:
831
-
832
- ```tsx
833
- import { render, screen, fireEvent } from "@testing-library/react-native";
834
- import { Gesture, GestureDetector } from "react-native-gesture-handler";
835
- import Animated, { useSharedValue, useAnimatedStyle } from "react-native-reanimated";
836
-
837
- function Card() {
838
- const pressed = useSharedValue(false);
839
- const style = useAnimatedStyle(() => ({ opacity: pressed.value ? 0.5 : 1 }));
840
- const tap = Gesture.Tap().onStart(() => {
841
- pressed.value = true;
842
- });
843
- return (
844
- <GestureDetector gesture={tap}>
845
- <Animated.View testID="card" style={style} />
846
- </GestureDetector>
847
- );
848
- }
849
-
850
- test("card renders at full opacity", async () => {
851
- await render(<Card />);
852
- expect(screen.getByTestId("card")).toHaveAnimatedStyle({ opacity: 1 });
853
- });
854
- ```
855
-
856
- > RNGH's `Pressable` is also exported by the preset and mirrors React Native's `Pressable` (including not firing `onPress` when `disabled`), so you can swap `import { Pressable } from 'react-native-gesture-handler'` straight into tests.
857
-
858
- ### TypeScript
859
-
860
- To type the matchers on `expect()`, add the matcher types to your `tsconfig.json`:
861
-
862
- ```jsonc
863
- {
864
- "compilerOptions": {
865
- "types": ["vitest-native/matchers"],
866
- },
867
- }
868
- ```
869
-
870
- ---
871
-
872
- ## Snapshot Serializer
873
-
874
- A snapshot serializer is auto-registered that produces clean, JSX-like output for React Native components. Instead of deeply nested `ReactTestInstance` objects, snapshots read naturally:
875
-
876
- ```
877
- <View>
878
- <Text
879
- style={
880
- {
881
- "fontSize": 18,
882
- }
883
- }
884
- >
885
- Hello, World
886
- </Text>
887
- </View>
888
- ```
889
-
890
- No configuration is required. The serializer is active for all snapshot tests automatically.
891
-
892
- ---
893
-
894
- ## Platform Extensions
895
-
896
- The plugin resolves platform-specific files following React Native conventions. When `platform` is set to `'ios'` (the default), imports resolve in this order:
897
-
898
- 1. `./Component.ios.ts`
899
- 2. `./Component.native.ts`
900
- 3. `./Component.ts`
901
-
902
- When `platform` is `'android'`:
903
-
904
- 1. `./Component.android.ts`
905
- 2. `./Component.native.ts`
906
- 3. `./Component.ts`
907
-
908
- This works for all supported extensions: `.ts`, `.tsx`, `.js`, `.jsx`.
909
-
910
- ```ts
911
- // vitest.config.ts -- test Android-specific code
912
- export default defineConfig({
913
- plugins: [reactNative({ platform: "android" })],
914
- });
915
- ```
916
-
917
- Platform resolution applies both to your app/test code (resolved by Vite) **and** to
918
- third-party `node_modules` packages with platform-specific files (e.g.
919
- `@react-navigation`'s `useLinking.native.js`). The latter matters because Vitest
920
- externalizes most `node_modules` dependencies — they load through Node, whose resolver
921
- has no notion of `.native.js`. The native engine fills that gap so externalized packages
922
- resolve the same `.native`/`.ios`/`.android` variant Metro would, instead of silently
923
- falling back to the default (often web) file.
924
-
925
- ---
926
-
927
- ## Assets
928
-
929
- Image, font, video, and audio imports evaluate to what Metro gives an app: a number, the id under which the asset is registered with React Native's asset registry. The registered descriptor is the one Metro builds — `name`, `type`, `scales`, `hash`, and for images `width` and `height` in points — so React Native's own asset handling works as on device:
930
-
931
- ```tsx
932
- const logo = require("./logo.png"); // a number
933
- Image.resolveAssetSource(logo); // { uri, width, height, scale, __packager_asset: true }
934
- <Image source={logo} />; // renders the resolved asset
935
- ```
936
-
937
- - `@2x`/`@3x` variants are grouped as Metro groups them, and a `.ios`/`.android` variant is preferred for the configured platform.
938
- - Dimensions are read from PNG, JPEG, GIF, BMP and WebP headers; other formats, and files that are not valid images, register without them.
939
- - The native engine registers with React Native's real registry; the mock engine registers with the mock `AssetRegistry`, which its `Image.resolveAssetSource` reads.
940
- - A snapshot shows the id (a number) where it used to show the file name. Ids follow registration order within a test file, so they are stable for that file.
941
-
942
- Built-in extensions include common formats like `.png`, `.jpg`, `.gif`, `.svg`, `.mp4`, `.ttf`, `.otf`, and more. To add additional extensions:
943
-
944
- ```ts
945
- reactNative({
946
- assetExts: [".lottie", ".m4b"],
947
- });
948
- ```
949
-
950
- ---
951
-
952
- ## Diagnostics
953
-
954
- Enable verbose logging to see exactly what the plugin is doing during configuration and module resolution:
955
-
956
- ```ts
957
- reactNative({
958
- diagnostics: true,
959
- });
960
- ```
961
-
962
- This prints details about which presets were detected, which modules are being mocked, and how imports are resolved. Useful for debugging unexpected behavior.
963
-
964
- ---
965
-
966
- ## Support Policy
967
-
968
- The stock `mock` and `native` engines are release-supported: regressions in their documented
969
- version ranges block pull requests and releases. The `hotRuntime` option is experimental because
970
- Vitest labels the custom-pool API it depends on experimental; it has the same correctness suite,
971
- isolation soak, and recycling gates, but may require a minor-version adaptation when Vitest changes
972
- that API.
973
-
974
- Every release must pass:
975
-
976
- - Linux on Node 22.13 (with RNTL 12, 13 and 14) and 24, plus macOS and Windows on Node 22.13.
977
- - The mock, native iOS, native Android, hot-runtime, isolation, and 100-file soak suites.
978
- - React Native 0.81–0.88 against both locked and newest-supported Vitest, plus the Vitest 4 floor
979
- on 0.81 and 0.88.
980
- - Vitest's own behaviour under the defaults, on Vitest 5 and the Vitest 4 floor: config and CLI
981
- flags, projects, watch mode, the jsdom and happy-dom environments, `--typecheck`, `vitest bench`,
982
- and the HTML reporter.
983
- - Packed consumers: bare RN 0.83/RNTL 12, a Jest-migration project, Expo SDK 58/RNTL 14 (with
984
- expo-router and a `migrate`-generated jest-expo config), Expo SDK 57/RNTL 13 (with expo-router), a mock-engine RNTL 14 project, npm- and
985
- pnpm-workspace monorepos on Vite 8, and an RN 0.86 Android project.
986
- - Packed V8 and Istanbul coverage maps/counts matching default isolation exactly under hot workers.
987
- - Mock-versus-real-RN behavioral cross-checks, example-app tests, typecheck, lint, formatting, and
988
- package export analysis.
989
-
990
- Current React Native edge releases are also tested weekly. See
991
- [the release-readiness policy](docs/release-readiness.md) for the exact gates and stability labels.
992
-
993
- For what is *promised* rather than what is tested — which exports and options are protected by
994
- semver, which are experimental, how the version ranges above may move, and what 1.0 will mean —
995
- see [versioning and stability](docs/versioning.md).
996
-
997
- ---
998
-
999
- ## Requirements
144
+ Thanks to everyone who has opened an issue or a pull request, or landed a commit. Each one has
145
+ shaped vitest-native.
1000
146
 
1001
- | Dependency | Supported version |
1002
- | -------------------------------------------- | ----------------------------------------- |
1003
- | `react` | >= 18; use RN's matching React version |
1004
- | `vite` | ^6.4.2, ^7.3.2, or ^8.0.5 |
1005
- | `vitest` | 4.x or 5.x |
1006
- | `node` | 22.13+ on Node 22, or 24.3+ |
1007
- | `react-native` (native engine) | 0.81–0.88 validated |
1008
- | `@react-native/babel-preset` (native engine) | Match the installed React Native minor |
1009
- | `@testing-library/react-native` (optional) | 12.x, 13.x, or 14.x |
1010
-
1011
- Node 20 reached end of life in April 2026. Node 22.13 is the first Node 22 that both RNTL 14 and the
1012
- engine's CommonJS entry points (`require(esm)`) support. On Node 24.0–24.2, `jest.mock`,
1013
- `jest.isolateModules` and `jest.resetModules` do not reach modules Node loads, with either loader.
1014
- Node 23 is past its end of life. RNTL 14 uses async rendering APIs.
1015
-
1016
- ---
147
+ <!-- contributors:start -->
148
+ See the [contributors on GitHub](https://github.com/danfry1/vitest-native#contributors).
149
+ <!-- contributors:end -->
1017
150
 
1018
151
  ## License
1019
152