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