vitest-native 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,9 +2,11 @@
2
2
 
3
3
  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
4
 
5
- > **Beta.** The real-RN engine is validated against real apps (react-native-paper, the obytes template, Rocket.Chat) across React Native 0.81–0.84, with a CI-gated behavioral cross-check against real RN. Some APIs may still shift before 1.0.
5
+ > **Beta.** The release-supported native engine is validated across React Native 0.81–0.86,
6
+ > Vite 6–8, Vitest 4, RNTL 12–14, bare apps, Expo 56, and hoisted monorepos. The optional
7
+ > hot runtime remains experimental because it uses Vitest's experimental custom-pool APIs.
6
8
  >
7
- > Spiritual 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+).
9
+ > 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).
8
10
 
9
11
  ---
10
12
 
@@ -27,6 +29,7 @@ Run your React Native tests under Vitest, against **real React Native** — the
27
29
  - [Platform Extensions](#platform-extensions)
28
30
  - [Asset Stubs](#asset-stubs)
29
31
  - [Diagnostics](#diagnostics)
32
+ - [Support Policy](#support-policy)
30
33
  - [Requirements](#requirements)
31
34
  - [License](#license)
32
35
 
@@ -64,6 +67,16 @@ yarn add -D vitest-native
64
67
  pnpm add -D vitest-native
65
68
  ```
66
69
 
70
+ A real React Native project already provides what the native engine needs —
71
+ `react-native`, `@react-native/babel-preset`, and `@babel/core`. Add
72
+ `@testing-library/react-native` if you don't have it yet (the examples below use it):
73
+
74
+ ```bash
75
+ npm install -D @testing-library/react-native
76
+ ```
77
+
78
+ See [Requirements](#requirements) for exact versions.
79
+
67
80
  ---
68
81
 
69
82
  ## Quick Start
@@ -71,8 +84,8 @@ pnpm add -D vitest-native
71
84
  Create or update your `vitest.config.ts`:
72
85
 
73
86
  ```ts
74
- import { defineConfig } from 'vitest/config';
75
- import { reactNative } from 'vitest-native';
87
+ import { defineConfig } from "vitest/config";
88
+ import { reactNative } from "vitest-native";
76
89
 
77
90
  export default defineConfig({
78
91
  plugins: [reactNative()],
@@ -82,8 +95,9 @@ export default defineConfig({
82
95
  That is it. Write a test:
83
96
 
84
97
  ```tsx
85
- import { render, screen } from '@testing-library/react-native';
86
- import { View, Text } from 'react-native';
98
+ import { test, expect } from "vitest";
99
+ import { render, screen } from "@testing-library/react-native";
100
+ import { View, Text } from "react-native";
87
101
 
88
102
  function Greeting({ name }: { name: string }) {
89
103
  return (
@@ -93,12 +107,17 @@ function Greeting({ name }: { name: string }) {
93
107
  );
94
108
  }
95
109
 
96
- test('renders a greeting', () => {
97
- render(<Greeting name="World" />);
98
- expect(screen.getByText('Hello, World')).toBeTruthy();
110
+ test("renders a greeting", async () => {
111
+ await render(<Greeting name="World" />);
112
+ expect(screen.getByText("Hello, World")).toBeTruthy();
99
113
  });
100
114
  ```
101
115
 
116
+ > Prefer Jest-style globals (`test`/`expect` without imports)? Set
117
+ > `test: { globals: true }` in your Vitest config. vitest-native does not enable the full
118
+ > globals mode; it only exposes `expect` when RNTL needs it to register matchers.
119
+ > Awaiting `render` works with RNTL 12–13 and is required by RNTL 14.
120
+
102
121
  Run it:
103
122
 
104
123
  ```bash
@@ -112,32 +131,35 @@ npx vitest
112
131
  The `reactNative()` function accepts an optional configuration object:
113
132
 
114
133
  ```ts
115
- import { defineConfig } from 'vitest/config';
116
- import { reactNative } from 'vitest-native';
134
+ import { defineConfig } from "vitest/config";
135
+ import { reactNative } from "vitest-native";
117
136
 
118
137
  export default defineConfig({
119
138
  plugins: [
120
139
  reactNative({
121
- engine: 'auto', // 'auto' | 'mock' | 'native' — auto → native when RN's babel deps are present, else mock
122
- platform: 'ios', // 'ios' | 'android' (default: 'ios')
123
- presets: [], // Preset[] -- omit for auto-detect
124
- mocks: {}, // Custom mock overrides for the react-native module
125
- diagnostics: false, // Enable verbose logging
126
- assetExts: ['.lottie'], // Additional asset extensions to stub
140
+ engine: "auto", // 'auto' | 'mock' | 'native' — auto → native when RN's babel deps are present, else mock
141
+ platform: "ios", // 'ios' | 'android' (default: 'ios')
142
+ presets: [], // Preset[] -- omit for auto-detect
143
+ mocks: {}, // Custom mock overrides for the react-native module
144
+ diagnostics: false, // Enable verbose logging
145
+ assetExts: [".lottie"], // Additional asset extensions to stub
146
+ transform: [], // Extra native-engine packages to Flow/TS transform
147
+ hotRuntime: false, // Experimental persistent RN workers
127
148
  }),
128
149
  ],
129
150
  });
130
151
  ```
131
152
 
132
- | Option | Type | Default | Description |
133
- |---|---|---|---|
134
- | `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. |
135
- | `platform` | `'ios' \| 'android'` | `'ios'` | Target platform. Controls `Platform.OS`, version defaults, and file extension resolution. |
136
- | `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. |
137
- | `mocks` | `Record<string, any>` | `{}` | 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. |
138
- | `diagnostics` | `boolean` | `false` | Log plugin activity to the console for debugging. |
139
- | `assetExts` | `string[]` | `[]` | Additional file extensions to stub as asset imports (beyond the built-in set). |
140
- | `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. |
153
+ | Option | Type | Default | Description |
154
+ | ------------- | ------------------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
155
+ | `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. |
156
+ | `platform` | `'ios' \| 'android'` | `'ios'` | Target platform. Controls `Platform.OS`, version defaults, and file extension resolution. |
157
+ | `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. |
158
+ | `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. |
159
+ | `diagnostics` | `boolean` | `false` | Log plugin activity to the console for debugging. |
160
+ | `assetExts` | `string[]` | `[]` | Additional file extensions to stub as asset imports (beyond the built-in set). |
161
+ | `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. |
162
+ | `hotRuntime` | `boolean \| HotRuntimeOptions` | `false` | **Experimental, `engine: 'native'` only.** Reuse workers while keeping app/test modules isolated per file. See [Hot runtime](#hot-runtime). |
141
163
 
142
164
  ### `engine`
143
165
 
@@ -153,13 +175,13 @@ Choose how React Native is provided to your tests:
153
175
  - `'mock'` — a lightweight, pure-JS reimplementation of React Native with **zero extra
154
176
  dependencies**. Best for pure-logic/unit tests, maximum determinism, or when you can't
155
177
  add the babel deps. Like Jest's preset, it is a simplification — see [Fidelity](#fidelity).
156
- - `'auto'` *(default)* — picks automatically, and **resolves to `'native'`** whenever
178
+ - `'auto'` _(default)_ — picks automatically, and **resolves to `'native'`** whenever
157
179
  `@react-native/babel-preset` and `@babel/core` are present (i.e. in any real RN app). It
158
180
  falls back to `'mock'` only when those deps are absent, printing one line to explain why.
159
181
  So `reactNative()` with no options runs real React Native. Set `engine: 'mock'` to opt out.
160
182
 
161
183
  ```ts
162
- reactNative({ engine: 'native' })
184
+ reactNative({ engine: "native" });
163
185
  ```
164
186
 
165
187
  #### Fidelity
@@ -168,64 +190,104 @@ Jest's `react-native` preset replaces many real modules with stubs, so behavior
168
190
  don't implement passes silently. The `native` engine runs the real implementations, so
169
191
  those checks actually run. For example:
170
192
 
171
- | Behavior | `engine: 'native'` (real RN) | Jest `react-native` preset |
172
- |---|---|---|
173
- | `Linking.openURL(123)` | throws `Invalid URL: should be a string` | accepts without validating |
174
- | `Linking.openURL('')` | throws `Invalid URL: cannot be empty` | accepts without validating |
175
- | `<Text>` host props | `accessible`, `allowFontScaling`, `ellipsizeMode` computed by real `Text.js` | not set |
193
+ | Behavior | `engine: 'native'` (real RN) | Jest `react-native` preset |
194
+ | ---------------------- | ---------------------------------------------------------------------------- | -------------------------- |
195
+ | `Linking.openURL(123)` | throws `Invalid URL: should be a string` | accepts without validating |
196
+ | `Linking.openURL('')` | throws `Invalid URL: cannot be empty` | accepts without validating |
197
+ | `<Text>` host props | `accessible`, `allowFontScaling`, `ellipsizeMode` computed by real `Text.js` | not set |
176
198
 
177
199
  The `mock` engine is a simplification too, so it diverges from real RN the same way — reach
178
200
  for `native` when a false pass would be costly. These specific differences are produced by
179
201
  the cross-check/fidelity harnesses in the repository's `bench/` directory.
180
202
 
203
+ #### Hot runtime
204
+
205
+ `engine: 'native'` normally uses Vitest's safest isolation model: each test file gets a fresh
206
+ worker, so React Native reloads for every file. Large suites can opt into persistent workers:
207
+
208
+ ```ts
209
+ reactNative({
210
+ engine: "native",
211
+ hotRuntime: true,
212
+ });
213
+ ```
214
+
215
+ The hot runtime keeps React Native's externalized module graph resident while Vitest still resets
216
+ the app/test module graph for every file. It also restores direct `process.env` mutations,
217
+ file-created globals, RN event subscriptions, dimensions, timers, and plugin mock state between
218
+ files. A dedicated one-worker CI test exercises this cross-file isolation contract.
219
+
220
+ For additional leak containment:
221
+
222
+ ```ts
223
+ reactNative({
224
+ engine: "native",
225
+ hotRuntime: {
226
+ recycleAfterFiles: 100,
227
+ memoryLimit: 512 * 1024 * 1024,
228
+ preserveGlobals: ["MY_RESIDENT_LIBRARY_REGISTRY"],
229
+ },
230
+ });
231
+ ```
232
+
233
+ Recycling is applied between Vitest scheduler tasks. Vitest can place multiple files in one task,
234
+ especially with `maxWorkers: 1`, so a worker cannot be retired in the middle of that batch. Use
235
+ more than one worker when strict per-file retirement matters. `preserveGlobals` is an exact
236
+ allowlist for registries created by resident external dependencies; Storybook's preview registry
237
+ is preserved automatically.
238
+
239
+ This mode uses Vitest's custom pool and worker APIs, so it remains experimental. CI runs the
240
+ complete native suite under both the lockfile Vitest and the newest supported Vitest 4 release,
241
+ plus a generated 100-file isolation soak and an end-to-end memory-triggered recycling test.
242
+
181
243
  ---
182
244
 
183
245
  ## Mocked Components and APIs
184
246
 
185
247
  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.
186
248
 
187
- ### Components (21)
249
+ ### Components (24)
188
250
 
189
- | Component | Component | Component |
190
- |---|---|---|
191
- | View | Text | Image |
192
- | TextInput | ScrollView | FlatList |
193
- | SectionList | Modal | Pressable |
194
- | TouchableOpacity | TouchableHighlight | TouchableWithoutFeedback |
195
- | TouchableNativeFeedback | ActivityIndicator | Button |
196
- | Switch | RefreshControl | StatusBar |
197
- | SafeAreaView | KeyboardAvoidingView | ImageBackground |
198
- | VirtualizedList | InputAccessoryView | DrawerLayoutAndroid |
251
+ | Component | Component | Component |
252
+ | ----------------------- | -------------------- | ------------------------ |
253
+ | View | Text | Image |
254
+ | TextInput | ScrollView | FlatList |
255
+ | SectionList | Modal | Pressable |
256
+ | TouchableOpacity | TouchableHighlight | TouchableWithoutFeedback |
257
+ | TouchableNativeFeedback | ActivityIndicator | Button |
258
+ | Switch | RefreshControl | StatusBar |
259
+ | SafeAreaView | KeyboardAvoidingView | ImageBackground |
260
+ | VirtualizedList | InputAccessoryView | DrawerLayoutAndroid |
199
261
 
200
262
  ### APIs (25+)
201
263
 
202
- | API | API | API |
203
- |---|---|---|
204
- | Platform | Dimensions | StyleSheet |
205
- | Animated | Alert | Linking |
206
- | AppState | Keyboard | BackHandler |
207
- | Vibration | PermissionsAndroid | Appearance |
208
- | PixelRatio | LayoutAnimation | Clipboard |
209
- | Share | AccessibilityInfo | InteractionManager |
210
- | PanResponder | ToastAndroid | ActionSheetIOS |
211
- | LogBox | Easing | I18nManager |
212
- | DeviceEventEmitter | | |
264
+ | API | API | API |
265
+ | ------------------ | ------------------ | ------------------ |
266
+ | Platform | Dimensions | StyleSheet |
267
+ | Animated | Alert | Linking |
268
+ | AppState | Keyboard | BackHandler |
269
+ | Vibration | PermissionsAndroid | Appearance |
270
+ | PixelRatio | LayoutAnimation | Clipboard |
271
+ | Share | AccessibilityInfo | InteractionManager |
272
+ | PanResponder | ToastAndroid | ActionSheetIOS |
273
+ | LogBox | Easing | I18nManager |
274
+ | DeviceEventEmitter | | |
213
275
 
214
276
  ### Native Bridge
215
277
 
216
- | Export | Description |
217
- |---|---|
218
- | `NativeModules` | Proxy that returns no-op modules for any key |
219
- | `TurboModuleRegistry` | Proxy with `getEnforcing` / `get` stubs |
220
- | `UIManager` | Stubbed layout manager |
221
- | `NativeEventEmitter` | Event emitter constructor mock |
222
- | `requireNativeComponent` | Returns a named component mock |
278
+ | Export | Description |
279
+ | ------------------------ | -------------------------------------------- |
280
+ | `NativeModules` | Proxy that returns no-op modules for any key |
281
+ | `TurboModuleRegistry` | Proxy with `getEnforcing` / `get` stubs |
282
+ | `UIManager` | Stubbed layout manager |
283
+ | `NativeEventEmitter` | Event emitter constructor mock |
284
+ | `requireNativeComponent` | Returns a named component mock |
223
285
 
224
286
  ### Hooks
225
287
 
226
- | Hook | Default Value |
227
- |---|---|
228
- | `useColorScheme` | `'light'` |
288
+ | Hook | Default Value |
289
+ | --------------------- | ----------------------------------------------------- |
290
+ | `useColorScheme` | `'light'` |
229
291
  | `useWindowDimensions` | `{ width: 390, height: 844, scale: 3, fontScale: 1 }` |
230
292
 
231
293
  ---
@@ -241,13 +303,16 @@ vitest-native ports tests from React Native's own test suite (Flow stripped, Jes
241
303
  - **Interpolation** — 12 numeric and string range mapping tests, including string output ranges (`deg`/`%`/arbitrary suffixes) and extrapolate modes (extend/clamp/identity)
242
304
  - **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
243
305
 
244
- 102 tests ported from React Native's own test suite, all passing (`vitest run tests/rn-conformance/`). A few edge cases — hex-colour interpolation and infinite input ranges — are skipped and documented in the test files.
306
+ 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/`).
245
307
 
246
308
  ---
247
309
 
248
310
  ## Test Helpers
249
311
 
250
- Import helpers from `vitest-native/helpers` to control mock state during tests.
312
+ Import helpers from `vitest-native/helpers` to control test state. `setDimensions`,
313
+ `setColorScheme`, `setInsets`, `mockNativeModule`, and `resetAllMocks` work under both engines.
314
+ `setPlatform` is mock-engine-only because the native engine selects platform files while loading
315
+ the module graph.
251
316
 
252
317
  ```ts
253
318
  import {
@@ -257,31 +322,36 @@ import {
257
322
  setInsets,
258
323
  mockNativeModule,
259
324
  resetAllMocks,
260
- } from 'vitest-native/helpers';
325
+ } from "vitest-native/helpers";
261
326
  ```
262
327
 
263
328
  ### `setPlatform(os)`
264
329
 
265
- Switch the platform for the current test. Updates `Platform.OS`, `Platform.Version`, and `Platform.select`.
330
+ Switch the platform for the current test under `engine: 'mock'`. Updates `Platform.OS`,
331
+ `Platform.Version`, and `Platform.select`.
266
332
 
267
333
  ```ts
268
- import { setPlatform } from 'vitest-native/helpers';
334
+ import { setPlatform } from "vitest-native/helpers";
269
335
 
270
- test('renders Android-specific UI', () => {
271
- setPlatform('android');
336
+ test("renders Android-specific UI", () => {
337
+ setPlatform("android");
272
338
  // Platform.OS is now 'android', Platform.Version is 34
273
339
  // Platform.select({ ios: 'A', android: 'B' }) returns 'B'
274
340
  });
275
341
  ```
276
342
 
343
+ Under `engine: 'native'`, configure `reactNative({ platform: 'android' })` or use separate Vitest
344
+ projects. Calling `setPlatform()` there throws because changing `Platform.OS` after platform-specific
345
+ modules have resolved would create an inconsistent graph.
346
+
277
347
  ### `setDimensions(dims)`
278
348
 
279
349
  Update `Dimensions.get()` and the `useWindowDimensions` hook return value.
280
350
 
281
351
  ```ts
282
- import { setDimensions } from 'vitest-native/helpers';
352
+ import { setDimensions } from "vitest-native/helpers";
283
353
 
284
- test('adapts to tablet dimensions', () => {
354
+ test("adapts to tablet dimensions", () => {
285
355
  setDimensions({ width: 768, height: 1024, scale: 2, fontScale: 1 });
286
356
  // Dimensions.get('window') returns { width: 768, height: 1024, ... }
287
357
  // useWindowDimensions() returns the same
@@ -293,10 +363,10 @@ test('adapts to tablet dimensions', () => {
293
363
  Switch the color scheme. Affects `Appearance.getColorScheme()` and the `useColorScheme` hook.
294
364
 
295
365
  ```ts
296
- import { setColorScheme } from 'vitest-native/helpers';
366
+ import { setColorScheme } from "vitest-native/helpers";
297
367
 
298
- test('renders dark mode styles', () => {
299
- setColorScheme('dark');
368
+ test("renders dark mode styles", () => {
369
+ setColorScheme("dark");
300
370
  // useColorScheme() returns 'dark'
301
371
  // Appearance.getColorScheme() returns 'dark'
302
372
  });
@@ -307,9 +377,9 @@ test('renders dark mode styles', () => {
307
377
  Update the safe area insets returned by `useSafeAreaInsets()` from `react-native-safe-area-context`. Requires the `safeAreaContext` preset to be active.
308
378
 
309
379
  ```ts
310
- import { setInsets } from 'vitest-native/helpers';
380
+ import { setInsets } from "vitest-native/helpers";
311
381
 
312
- test('renders with no bottom inset (Android)', () => {
382
+ test("renders with no bottom inset (Android)", () => {
313
383
  setInsets({ top: 24, bottom: 0 });
314
384
  // useSafeAreaInsets() returns { top: 24, right: 0, bottom: 0, left: 0 }
315
385
  });
@@ -317,27 +387,31 @@ test('renders with no bottom inset (Android)', () => {
317
387
 
318
388
  ### `mockNativeModule(name, impl)`
319
389
 
320
- Register a custom native module mock. The module becomes available via `NativeModules[name]`.
390
+ Register a custom native module mock. The module becomes available through both
391
+ `NativeModules[name]` and `TurboModuleRegistry.get(name)`.
321
392
 
322
393
  ```ts
323
- import { mockNativeModule } from 'vitest-native/helpers';
394
+ import { mockNativeModule } from "vitest-native/helpers";
324
395
 
325
- test('uses a custom native module', () => {
326
- mockNativeModule('MyBridge', {
396
+ test("uses a custom native module", () => {
397
+ mockNativeModule("MyBridge", {
327
398
  getValue: vi.fn().mockResolvedValue(42),
328
399
  });
329
400
 
330
- const { NativeModules } = require('react-native');
401
+ const { NativeModules } = require("react-native");
331
402
  await expect(NativeModules.MyBridge.getValue()).resolves.toBe(42);
332
403
  });
333
404
  ```
334
405
 
335
406
  ### `resetAllMocks()`
336
407
 
337
- Reset all mocks to their default state. Restores platform to iOS, dimensions to iPhone 14 Pro defaults (390x844), color scheme to `'light'`, safe area insets to iPhone defaults, clears AsyncStorage data, clears all mock call history, and undoes any `mockNativeModule` calls.
408
+ Reset plugin-controlled state. Under the mock engine this restores the mock defaults, including
409
+ iOS platform defaults. Under the native engine it restores the configured platform's initial
410
+ dimensions and color scheme. Both engines reset active preset stores, clear mock call history, and
411
+ undo `mockNativeModule` calls.
338
412
 
339
413
  ```ts
340
- import { resetAllMocks } from 'vitest-native/helpers';
414
+ import { resetAllMocks } from "vitest-native/helpers";
341
415
 
342
416
  afterEach(() => {
343
417
  resetAllMocks();
@@ -350,30 +424,26 @@ afterEach(() => {
350
424
 
351
425
  When the `presets` option is omitted, the plugin scans your `node_modules` and automatically enables mocks for installed third-party libraries:
352
426
 
353
- | Package | What Gets Mocked |
354
- |---|---|
355
- | `react-native-reanimated` | Animated values, `useSharedValue`, `useAnimatedStyle`, layout animations |
356
- | `react-native-gesture-handler` | Gesture components, `GestureHandlerRootView`, state constants |
357
- | `react-native-safe-area-context` | `SafeAreaProvider`, `useSafeAreaInsets`, `SafeAreaView` |
358
- | `@react-navigation/native` | `NavigationContainer`, `useNavigation`, `useRoute` |
359
- | `@react-native-async-storage/async-storage` | `getItem`, `setItem`, `removeItem`, `clear`, `getAllKeys` |
360
- | `react-native-screens` | `enableScreens`, screen components |
361
- | `expo` | `expo-constants`, `expo-font`, `expo-asset`, `expo-splash-screen`, `expo-linking`, `expo-status-bar` |
427
+ | Package | What Gets Mocked |
428
+ | ------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
429
+ | `react-native-reanimated` | Animated values, `useSharedValue`, `useAnimatedStyle`, layout animations |
430
+ | `react-native-gesture-handler` | Gesture components, `GestureHandlerRootView`, state constants |
431
+ | `react-native-safe-area-context` | `SafeAreaProvider`, `useSafeAreaInsets`, `SafeAreaView` |
432
+ | `@react-navigation/native` | `NavigationContainer`, `useNavigation`, `useRoute` |
433
+ | `@react-native-async-storage/async-storage` | `getItem`, `setItem`, `removeItem`, `clear`, `getAllKeys` |
434
+ | `react-native-screens` | `enableScreens`, screen components |
435
+ | `expo` | `expo-constants`, `expo-font`, `expo-asset`, `expo-splash-screen`, `expo-linking`, `expo-status-bar` |
362
436
 
363
437
  Auto-detection means zero additional config for most projects. If you need to restrict which presets are active, pass them explicitly:
364
438
 
365
439
  ```ts
366
- import { defineConfig } from 'vitest/config';
367
- import { reactNative, presets } from 'vitest-native';
440
+ import { defineConfig } from "vitest/config";
441
+ import { reactNative, presets } from "vitest-native";
368
442
 
369
443
  export default defineConfig({
370
444
  plugins: [
371
445
  reactNative({
372
- presets: [
373
- presets.reanimated(),
374
- presets.gestureHandler(),
375
- presets.safeAreaContext(),
376
- ],
446
+ presets: [presets.reanimated(), presets.gestureHandler(), presets.safeAreaContext()],
377
447
  }),
378
448
  ],
379
449
  });
@@ -381,15 +451,19 @@ export default defineConfig({
381
451
 
382
452
  ### Available Presets
383
453
 
384
- | Import | Function |
385
- |---|---|
386
- | `presets.reanimated()` | react-native-reanimated |
387
- | `presets.gestureHandler()` | react-native-gesture-handler |
388
- | `presets.safeAreaContext()` | react-native-safe-area-context |
389
- | `presets.navigation()` | @react-navigation/native |
390
- | `presets.asyncStorage()` | @react-native-async-storage/async-storage |
391
- | `presets.screens()` | react-native-screens |
392
- | `presets.expo()` | Expo modules |
454
+ | Import | Function |
455
+ | --------------------------- | ----------------------------------------- |
456
+ | `presets.reanimated()` | react-native-reanimated |
457
+ | `presets.gestureHandler()` | react-native-gesture-handler |
458
+ | `presets.safeAreaContext()` | react-native-safe-area-context |
459
+ | `presets.navigation()` | @react-navigation/native |
460
+ | `presets.asyncStorage()` | @react-native-async-storage/async-storage |
461
+ | `presets.screens()` | react-native-screens |
462
+ | `presets.expo()` | Expo modules |
463
+ | `presets.deviceInfo()` | react-native-device-info |
464
+ | `presets.mmkv()` | react-native-mmkv |
465
+ | `presets.svg()` | react-native-svg |
466
+ | `presets.webview()` | react-native-webview |
393
467
 
394
468
  Presets apply under **both** engines: the mock engine and `engine: 'native'` (where they shadow each
395
469
  library's native runtime — worklets, native modules — exactly as Jest does, while the surrounding tree
@@ -402,14 +476,15 @@ The `expo` preset shadows the common Expo modules (`expo-constants`, `expo-statu
402
476
  imports those renders under the native engine with no extra setup — there's a gated proof in
403
477
  `tests-native/expo.test.tsx`. Two honest caveats:
404
478
 
405
- - **Expo modules without a preset** (e.g. `expo-image`, `expo-haptics`) still need a `vi.mock` or a
406
- custom preset, just as `jest-expo` ships a mock for each. The native engine externalizes them to
407
- Node, so importing the real native module would fail without a stand-in.
479
+ - **Expo modules without a built-in preset** (e.g. `expo-image`, `expo-haptics`) still need a
480
+ setup-file `vi.mock` at a Vite-managed boundary. The native engine externalizes native-side
481
+ libraries to Node, so imports made entirely inside that externalized graph cannot be intercepted
482
+ by Vitest's mocker.
408
483
  - **Expo SDK trails React Native.** Pin your `react-native` to the version your Expo SDK supports
409
484
  (which is within this plugin's validated range), not the newest RN release.
410
485
 
411
- Full Expo-app validation (a real Expo project's suite end-to-end) is on the roadmap; today the
412
- guarantee is the presets above plus standard `vi.mock` for the rest.
486
+ A packed Expo 56 consumer is installed from the release tarball and tested in CI. That gate covers
487
+ Expo preset auto-detection, `expo-constants`, `expo-status-bar`, real RN rendering, and RNTL 13.
413
488
 
414
489
  ---
415
490
 
@@ -445,11 +520,11 @@ suite (the `jest` global, `@jest/globals`, jest-native's extend-expect):
445
520
 
446
521
  ```ts
447
522
  // vitest.config.mts
448
- import { reactNative } from 'vitest-native';
449
- import { jestCompatAliases, jestCompatSetup } from 'vitest-native/jest-compat';
523
+ import { reactNative } from "vitest-native";
524
+ import { jestCompatAliases, jestCompatSetup } from "vitest-native/jest-compat";
450
525
 
451
526
  export default defineConfig({
452
- plugins: [reactNative({ engine: 'native' })],
527
+ plugins: [reactNative({ engine: "native" })],
453
528
  resolve: { alias: { ...jestCompatAliases() } },
454
529
  test: { globals: true, setupFiles: [jestCompatSetup] },
455
530
  });
@@ -474,7 +549,7 @@ npm i -D @react-native/babel-preset @babel/core
474
549
  To silence the notice and stay on mock deliberately, set `reactNative({ engine: 'mock' })`.
475
550
 
476
551
  **`vi.mock('some-rn-library')` doesn't take effect (native engine)**
477
- Under `engine: 'native'`, React Native and its native-side libraries are *externalized* to Node,
552
+ Under `engine: 'native'`, React Native and its native-side libraries are _externalized_ to Node,
478
553
  so they load outside Vite's module graph — and Vitest's mocker only intercepts modules inside that
479
554
  graph. Your **own** source modules mock normally; the gap is third-party RN-side packages. Options:
480
555
 
@@ -489,9 +564,10 @@ packages. If a dependency ships untranspiled Flow/TS, add it to the
489
564
  [`transform`](#plugin-options) allowlist.
490
565
 
491
566
  **My `babel.config.js` plugin isn't running**
492
- Transforms go through Vite/esbuild, not Babel, so custom Babel plugins don't apply. JSX (automatic
493
- runtime) and RN/preset Flow-stripping are handled for you; for anything else, prefer a Vite plugin
494
- or a preset.
567
+ Transforms go through Vite's JSX transformer, not your Babel config, so custom Babel plugins don't
568
+ apply. Vite 6–7 use esbuild and Vite 8 uses Oxc; the plugin configures the automatic JSX runtime for
569
+ both. RN/preset Flow-stripping is handled separately; for anything else, prefer a Vite plugin or a
570
+ preset.
495
571
 
496
572
  **Snapshots differ after switching from Jest or the mock engine**
497
573
  Real RN computes host props (e.g. `<Text>`'s `accessible`, `allowFontScaling`) that mocks omit, so
@@ -501,45 +577,47 @@ the tree is richer. Re-record once with `npx vitest -u` after migrating.
501
577
 
502
578
  ## RNTL Matchers
503
579
 
504
- When `@testing-library/react-native` v12.9 or later is installed, `vitest-native` auto-registers its custom matchers. No manual `extend(matchers)` call or setup file is needed.
580
+ When supported `@testing-library/react-native` 12–14 is installed, `vitest-native`
581
+ auto-registers its custom matchers across each major's export layout. No manual
582
+ `extend(matchers)` call or setup file is needed.
505
583
 
506
584
  The following matchers become available on `expect()`:
507
585
 
508
- | Matcher | Description |
509
- |---|---|
510
- | `toBeVisible()` | Element is visible |
511
- | `toBeEmptyElement()` | Element has no children |
512
- | `toBeEnabled()` | Element is not disabled |
513
- | `toBeDisabled()` | Element is disabled |
514
- | `toHaveTextContent(text)` | Element contains the given text |
515
- | `toHaveProp(name, value?)` | Element has the specified prop |
516
- | `toHaveStyle(style)` | Element has the specified styles |
517
- | `toBeOnTheScreen()` | Element is in the component tree |
518
- | `toContainElement(element)` | Element contains the given child |
586
+ | Matcher | Description |
587
+ | --------------------------------- | --------------------------------------------- |
588
+ | `toBeVisible()` | Element is visible |
589
+ | `toBeEmptyElement()` | Element has no children |
590
+ | `toBeEnabled()` | Element is not disabled |
591
+ | `toBeDisabled()` | Element is disabled |
592
+ | `toHaveTextContent(text)` | Element contains the given text |
593
+ | `toHaveProp(name, value?)` | Element has the specified prop |
594
+ | `toHaveStyle(style)` | Element has the specified styles |
595
+ | `toBeOnTheScreen()` | Element is in the component tree |
596
+ | `toContainElement(element)` | Element contains the given child |
519
597
  | `toHaveAccessibilityState(state)` | Element has the specified accessibility state |
520
598
  | `toHaveAccessibilityValue(value)` | Element has the specified accessibility value |
521
- | `toBeSelected()` | Element is selected |
522
- | `toBeChecked()` | Element is checked |
523
- | `toBePartiallyChecked()` | Element is partially checked |
524
- | `toBeBusy()` | Element is busy |
525
- | `toBeExpanded()` | Element is expanded |
526
- | `toBeCollapsed()` | Element is collapsed |
599
+ | `toBeSelected()` | Element is selected |
600
+ | `toBeChecked()` | Element is checked |
601
+ | `toBePartiallyChecked()` | Element is partially checked |
602
+ | `toBeBusy()` | Element is busy |
603
+ | `toBeExpanded()` | Element is expanded |
604
+ | `toBeCollapsed()` | Element is collapsed |
527
605
 
528
606
  ```tsx
529
- import { render, screen } from '@testing-library/react-native';
530
- import { View, Text } from 'react-native';
607
+ import { render, screen } from "@testing-library/react-native";
608
+ import { View, Text } from "react-native";
531
609
 
532
- test('greeting is visible with correct style', () => {
533
- render(
610
+ test("greeting is visible with correct style", async () => {
611
+ await render(
534
612
  <View>
535
- <Text style={{ color: 'red', fontSize: 18 }}>Hello</Text>
536
- </View>
613
+ <Text style={{ color: "red", fontSize: 18 }}>Hello</Text>
614
+ </View>,
537
615
  );
538
616
 
539
- const text = screen.getByText('Hello');
617
+ const text = screen.getByText("Hello");
540
618
  expect(text).toBeVisible();
541
- expect(text).toHaveStyle({ color: 'red' });
542
- expect(text).toHaveTextContent('Hello');
619
+ expect(text).toHaveStyle({ color: "red" });
620
+ expect(text).toHaveTextContent("Hello");
543
621
  });
544
622
  ```
545
623
 
@@ -549,16 +627,16 @@ test('greeting is visible with correct style', () => {
549
627
 
550
628
  `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.
551
629
 
552
- | Matcher | Description |
553
- |---|---|
630
+ | Matcher | Description |
631
+ | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
554
632
  | `toHaveAnimatedStyle(style, config?)` | Element's (flattened) style contains the given entries. Pass `{ shouldMatchAllProps: true }` to require an exact match. |
555
- | `toHaveAnimatedProps(props)` | Element's animated props contain the given entries. |
633
+ | `toHaveAnimatedProps(props)` | Element's animated props contain the given entries. |
556
634
 
557
635
  Because the `reanimated` preset resolves `useAnimatedStyle`/`useAnimatedProps` synchronously, the animated values land on the rendered element and these matchers read straight from it:
558
636
 
559
637
  ```tsx
560
- import { render, screen } from '@testing-library/react-native';
561
- import Animated, { useSharedValue, useAnimatedStyle } from 'react-native-reanimated';
638
+ import { render, screen } from "@testing-library/react-native";
639
+ import Animated, { useSharedValue, useAnimatedStyle } from "react-native-reanimated";
562
640
 
563
641
  function Skeleton({ visible }: { visible: boolean }) {
564
642
  const opacity = useSharedValue(visible ? 1 : 0);
@@ -566,9 +644,9 @@ function Skeleton({ visible }: { visible: boolean }) {
566
644
  return <Animated.View testID="bone" style={style} />;
567
645
  }
568
646
 
569
- test('starts with full opacity', () => {
570
- render(<Skeleton visible />);
571
- expect(screen.getByTestId('bone')).toHaveAnimatedStyle({ opacity: 1 });
647
+ test("starts with full opacity", async () => {
648
+ await render(<Skeleton visible />);
649
+ expect(screen.getByTestId("bone")).toHaveAnimatedStyle({ opacity: 1 });
572
650
  });
573
651
  ```
574
652
 
@@ -577,9 +655,9 @@ test('starts with full opacity', () => {
577
655
  Both libraries are auto-detected, so a component using a `Gesture` + `GestureDetector` driving an animated style needs no `vi.mock()` calls:
578
656
 
579
657
  ```tsx
580
- import { render, screen, fireEvent } from '@testing-library/react-native';
581
- import { Gesture, GestureDetector } from 'react-native-gesture-handler';
582
- import Animated, { useSharedValue, useAnimatedStyle } from 'react-native-reanimated';
658
+ import { render, screen, fireEvent } from "@testing-library/react-native";
659
+ import { Gesture, GestureDetector } from "react-native-gesture-handler";
660
+ import Animated, { useSharedValue, useAnimatedStyle } from "react-native-reanimated";
583
661
 
584
662
  function Card() {
585
663
  const pressed = useSharedValue(false);
@@ -594,9 +672,9 @@ function Card() {
594
672
  );
595
673
  }
596
674
 
597
- test('card renders at full opacity', () => {
598
- render(<Card />);
599
- expect(screen.getByTestId('card')).toHaveAnimatedStyle({ opacity: 1 });
675
+ test("card renders at full opacity", async () => {
676
+ await render(<Card />);
677
+ expect(screen.getByTestId("card")).toHaveAnimatedStyle({ opacity: 1 });
600
678
  });
601
679
  ```
602
680
 
@@ -609,8 +687,8 @@ To type the matchers on `expect()`, add the matcher types to your `tsconfig.json
609
687
  ```jsonc
610
688
  {
611
689
  "compilerOptions": {
612
- "types": ["vitest-native/matchers"]
613
- }
690
+ "types": ["vitest-native/matchers"],
691
+ },
614
692
  }
615
693
  ```
616
694
 
@@ -657,7 +735,7 @@ This works for all supported extensions: `.ts`, `.tsx`, `.js`, `.jsx`.
657
735
  ```ts
658
736
  // vitest.config.ts -- test Android-specific code
659
737
  export default defineConfig({
660
- plugins: [reactNative({ platform: 'android' })],
738
+ plugins: [reactNative({ platform: "android" })],
661
739
  });
662
740
  ```
663
741
 
@@ -668,7 +746,7 @@ export default defineConfig({
668
746
  Image, font, video, and audio imports are automatically stubbed. The import resolves to the filename string, so code that passes asset paths through continues to work without errors.
669
747
 
670
748
  ```ts
671
- import logo from './logo.png';
749
+ import logo from "./logo.png";
672
750
  // logo === 'logo.png'
673
751
  ```
674
752
 
@@ -676,8 +754,8 @@ Built-in extensions include common formats like `.png`, `.jpg`, `.gif`, `.svg`,
676
754
 
677
755
  ```ts
678
756
  reactNative({
679
- assetExts: ['.lottie', '.m4b'],
680
- })
757
+ assetExts: [".lottie", ".m4b"],
758
+ });
681
759
  ```
682
760
 
683
761
  ---
@@ -689,24 +767,50 @@ Enable verbose logging to see exactly what the plugin is doing during configurat
689
767
  ```ts
690
768
  reactNative({
691
769
  diagnostics: true,
692
- })
770
+ });
693
771
  ```
694
772
 
695
773
  This prints details about which presets were detected, which modules are being mocked, and how imports are resolved. Useful for debugging unexpected behavior.
696
774
 
697
775
  ---
698
776
 
777
+ ## Support Policy
778
+
779
+ The stock `mock` and `native` engines are release-supported: regressions in their documented
780
+ version ranges block pull requests and releases. The `hotRuntime` option is experimental because
781
+ Vitest labels the custom-pool API it depends on experimental; it has the same correctness suite,
782
+ isolation soak, and recycling gates, but may require a minor-version adaptation when Vitest changes
783
+ that API.
784
+
785
+ Every release must pass:
786
+
787
+ - Linux on Node 20.19 and 22.13, plus macOS and Windows on Node 22.13.
788
+ - The mock, native iOS, native Android, hot-runtime, isolation, and 100-file soak suites.
789
+ - React Native 0.81–0.85 against both locked and newest-supported Vitest 4.
790
+ - Packed bare RN 0.83/RNTL 12, Expo 56/RNTL 13, Vite 8 monorepo/RNTL 14, and RN 0.86 consumers.
791
+ - Mock-versus-real-RN behavioral cross-checks, example-app tests, typecheck, lint, formatting, and
792
+ package export analysis.
793
+
794
+ Current React Native edge releases are also tested weekly. See
795
+ [the release-readiness policy](docs/release-readiness.md) for the exact gates and stability labels.
796
+
797
+ ---
798
+
699
799
  ## Requirements
700
800
 
701
- | Dependency | Version |
702
- |---|---|
703
- | `react` | >= 18 |
704
- | `vite` | >= 5 |
705
- | `vitest` | >= 4 |
706
- | `node` | >= 20 |
707
- | `react-native` (native engine) | 0.81–0.84 validated |
708
- | `@react-native/babel-preset` (native engine) | `*` |
709
- | `@testing-library/react-native` (optional) | >= 12 |
801
+ | Dependency | Supported version |
802
+ | -------------------------------------------- | ----------------------------------------- |
803
+ | `react` | >= 18; use RN's matching React version |
804
+ | `vite` | ^6.4.2, ^7.3.2, or ^8.0.5 |
805
+ | `vitest` | 4.x |
806
+ | `node` | >= 20; RN/RNTL may impose a higher floor |
807
+ | `react-native` (native engine) | 0.81–0.86 validated |
808
+ | `@react-native/babel-preset` (native engine) | Match the installed React Native minor |
809
+ | `@testing-library/react-native` (optional) | 12.x, 13.x, or 14.x |
810
+
811
+ RNTL 14 requires Node 22.13 or 24+ and uses async rendering APIs. React Native 0.86 requires
812
+ Node 20.19.4, 22.13, or 24.3 or newer. Those are upstream requirements; the mock engine itself
813
+ continues to support Node 20.
710
814
 
711
815
  ---
712
816