vitest-native 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +268 -9
  3. package/dist/chunk-CZWwpsFl.cjs +43 -0
  4. package/dist/helpers.cjs +10 -0
  5. package/dist/helpers.d.cts +7 -1
  6. package/dist/helpers.d.mts +7 -1
  7. package/dist/helpers.mjs +10 -1
  8. package/dist/{index-CJqS-y_M.d.cts → index-CJIhukN_.d.mts} +58 -4
  9. package/dist/{index-h4vpIkQO.d.mts → index-DEB7OFaJ.d.cts} +60 -2
  10. package/dist/index.cjs +296 -35
  11. package/dist/index.d.cts +1 -1
  12. package/dist/index.d.mts +1 -1
  13. package/dist/index.mjs +292 -33
  14. package/dist/jest-compat/interop.mjs +30 -0
  15. package/dist/jest-compat/jest-globals.d.mts +3 -0
  16. package/dist/jest-compat/jest-globals.mjs +9 -0
  17. package/dist/jest-compat/noop.d.mts +3 -0
  18. package/dist/jest-compat/noop.mjs +7 -0
  19. package/dist/jest-compat/setup.d.mts +3 -0
  20. package/dist/jest-compat/setup.mjs +41 -0
  21. package/dist/jest-compat.cjs +109 -0
  22. package/dist/jest-compat.d.cts +38 -0
  23. package/dist/jest-compat.d.mts +38 -0
  24. package/dist/jest-compat.mjs +104 -0
  25. package/dist/matchers.cjs +69 -0
  26. package/dist/matchers.d.cts +51 -0
  27. package/dist/matchers.d.mts +51 -0
  28. package/dist/matchers.mjs +66 -0
  29. package/dist/native/boundary.mjs +225 -0
  30. package/dist/native/globals.mjs +112 -0
  31. package/dist/native/hooks.mjs +85 -0
  32. package/dist/native/loader.mjs +123 -0
  33. package/dist/native/match.mjs +9 -0
  34. package/dist/native/reset.mjs +170 -0
  35. package/dist/native/resolve.mjs +22 -0
  36. package/dist/native/runner.mjs +18 -0
  37. package/dist/native/setup.mjs +134 -0
  38. package/dist/native/transform.mjs +79 -0
  39. package/dist/native/worker.mjs +96 -0
  40. package/dist/pool-B4mWN3N5.cjs +60 -0
  41. package/dist/pool-oPTZiSXU.mjs +58 -0
  42. package/dist/{preset-map-Bt4dXkZO.cjs → preset-map-C3jxnkiX.cjs} +6 -1
  43. package/dist/{preset-map-D224CC5w.mjs → preset-map-OJm5IWuL.mjs} +6 -1
  44. package/dist/{presets-9Y4ssfiH.cjs → presets-2I68Ipyl.cjs} +768 -122
  45. package/dist/{presets-CWH0gtM0.mjs → presets-DOGXQzYT.mjs} +732 -87
  46. package/dist/presets.cjs +5 -1
  47. package/dist/presets.d.cts +2 -2
  48. package/dist/presets.d.mts +2 -2
  49. package/dist/presets.mjs +2 -2
  50. package/dist/setup.cjs +903 -121
  51. package/dist/setup.mjs +899 -118
  52. package/docs/migrating-from-jest.md +123 -0
  53. package/docs/migrating-from-vitest-react-native.md +109 -0
  54. package/package.json +67 -8
package/CHANGELOG.md CHANGED
@@ -1,5 +1,91 @@
1
1
  # vitest-native
2
2
 
3
+ ## 0.4.0
4
+
5
+ **The native engine is now the zero-config default.** `reactNative()` with no
6
+ options runs your tests against **real React Native** — the same JavaScript that
7
+ ships in your app — mocking only the native-module boundary. The pure-JS mock
8
+ engine remains as an explicit opt-in (`engine: 'mock'`). vitest-native positions
9
+ itself as the maintained continuation of
10
+ [`vitest-community/vitest-react-native`](https://github.com/vitest-community/vitest-react-native).
11
+
12
+ > Beta. The native engine is validated against real apps (react-native-paper, the
13
+ > obytes template, Rocket.Chat) across React Native 0.81–0.84, with a CI-gated
14
+ > behavioral cross-check against real RN. Some APIs may still shift before 1.0.
15
+
16
+ ### Breaking Changes
17
+
18
+ - **`engine: 'auto'` (the default) now resolves to `'native'`** whenever
19
+ `@react-native/babel-preset` and `@babel/core` are present — i.e. in any real RN
20
+ app. It falls back to `'mock'` only when those deps are absent, printing one line
21
+ to explain why. Previously `auto` always resolved to `mock`. Set
22
+ `engine: 'mock'` to keep the old behavior.
23
+
24
+ ### Native engine
25
+
26
+ - **Boundary hardening.** The native-module stub now honors RN's calling
27
+ conventions it previously broke: callback-style methods invoke the success
28
+ callback instead of hanging (fixes `AccessibilityInfo.*`, `Share.share`), and
29
+ promise-returning methods return a real `Promise` (fixes `Linking.canOpenURL`/
30
+ `openURL`, `Image.prefetch`/`getSize`). Backed by app-shaped stress suites
31
+ (`tests-native/stress*.test.tsx`) as a permanent regression gate.
32
+ - **`isolate: true` is the native-engine default** — the safe Vitest default.
33
+ Adversarial testing proved `isolate: false` leaks state across files at scale.
34
+ An opt-in **hot runtime** (`reactNative({ hotRuntime: true })`) reclaims the
35
+ speed safely via surgical per-file reset, for large suites.
36
+ - **`transform` allowlist** — extra `node_modules` packages whose untranspiled
37
+ source the native engine should strip (Flow/TS/JSX) as it loads them, for
38
+ third-party RN libraries (analogous to Jest's `transformIgnorePatterns`).
39
+ - **Presets apply under the native engine**, shadowing each library's native
40
+ runtime (worklets, native modules) the way Jest does — including transitively
41
+ imported presets — while the surrounding tree renders through real RN.
42
+ - **Expo**: the `expo` preset shadows the common Expo modules under the native
43
+ engine (gated proof in `tests-native/expo.test.tsx`).
44
+
45
+ ### Trust & tooling
46
+
47
+ - **Cross-check** — a CI-gated behavioral differential that runs the same probes
48
+ under `mock` and `native` and diffs them against real RN as the oracle. It is
49
+ how mock fidelity is proven (and it found two of the mock fixes below).
50
+ - **Vitest × RN CI matrix** — gates the native engine across RN 0.81–0.84 ×
51
+ Vitest {pinned, latest}, with the latest-Vitest column as a non-blocking canary.
52
+ - **Jest migration tooling** — a `vitest-native/jest-compat` entry (the `jest`
53
+ global, `@jest/globals`, jest-native extend-expect) plus auto-hoisting of
54
+ top-level `jest.mock` → `vi.mock` and automatic JSX runtime. Guides:
55
+ `docs/migrating-from-jest.md` and `docs/migrating-from-vitest-react-native.md`.
56
+
57
+ ### Presets & matchers
58
+
59
+ - `react-native-gesture-handler` preset now exports `Pressable` (mirroring RN's,
60
+ including suppressing press handlers when `disabled`).
61
+ - `toHaveAnimatedStyle` / `toHaveAnimatedProps` are auto-registered on `expect()`,
62
+ replacing reanimated's Jest-only `setUpTests()` matchers. Opt into types with
63
+ `"types": ["vitest-native/matchers"]`.
64
+ - New presets: `react-native-device-info`, `react-native-mmkv`, `react-native-svg`,
65
+ `react-native-webview`; navigation preset covers drawer/bottom-tabs/elements.
66
+
67
+ ### Mock-engine fidelity fixes
68
+
69
+ - Disabled `Pressable`/`Touchable` mocks now suppress press handlers.
70
+ - `StyleSheet.hairlineWidth` is derived from the pixel ratio (≈`1/3` at scale 3)
71
+ instead of a hardcoded `0.5`, matching real RN.
72
+ - `Animated.Value.interpolate()` supports string output ranges (e.g.
73
+ `["0deg", "360deg"]`, `["0%", "100%"]`), preserving the unit/suffix.
74
+
75
+ ## 0.3.0
76
+
77
+ ### Minor Changes
78
+
79
+ - Add RN conformance test suite — 75 tests ported from React Native's own test suite (Animated, processColor, flattenStyle, Interpolation) to validate mock behavioral parity
80
+ - Add Animated orchestration: `sequence` chains via callbacks, `parallel` waits for all, `loop` supports finite/indefinite iterations with `resetBeforeIteration`
81
+ - Add Animated value tracking: `timing`/`spring` with an `AnimatedValue` as `toValue` track source changes via listener
82
+ - Add Animated.Color, diffClamp tracking, interpolation extrapolate/easing, toJSON support
83
+ - Expand reanimated preset: 44 entering/exiting animations, 7 layout transitions, `useAnimatedReaction`, `useAnimatedKeyboard`, `useReducedMotion`, `useFrameCallback`, `makeMutable`, `SharedTransition`, `ReduceMotion`/`KeyboardState` enums
84
+ - Add `@react-navigation/drawer` preset with `createDrawerNavigator`
85
+ - Add `setInsets()` helper for safe area context testing
86
+ - Add inter-test isolation: `resetAllMocks()` now resets AsyncStorage store and safe area insets
87
+ - 1136 tests passing across 30 files
88
+
3
89
  ## 0.2.1
4
90
 
5
91
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # vitest-native
2
2
 
3
- A Vitest plugin for React Native. One install, zero config.
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
+
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.
6
+ >
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+).
4
8
 
5
9
  ---
6
10
 
@@ -11,9 +15,14 @@ A Vitest plugin for React Native. One install, zero config.
11
15
  - [Quick Start](#quick-start)
12
16
  - [Plugin Options](#plugin-options)
13
17
  - [Mocked Components and APIs](#mocked-components-and-apis)
18
+ - [React Native Test Suite Conformance](#react-native-test-suite-conformance)
14
19
  - [Test Helpers](#test-helpers)
15
20
  - [Auto-Detect Presets](#auto-detect-presets)
21
+ - [Migrating from `vitest-react-native`](#migrating-from-vitest-react-native)
22
+ - [Migrating from Jest](#migrating-from-jest)
23
+ - [Troubleshooting](#troubleshooting)
16
24
  - [RNTL Matchers](#rntl-matchers)
25
+ - [Animated Matchers (Reanimated)](#animated-matchers-reanimated)
17
26
  - [Snapshot Serializer](#snapshot-serializer)
18
27
  - [Platform Extensions](#platform-extensions)
19
28
  - [Asset Stubs](#asset-stubs)
@@ -29,13 +38,13 @@ Testing React Native code with Jest has traditionally required a patchwork of co
29
38
 
30
39
  `vitest-native` replaces all of that with a single Vite plugin:
31
40
 
32
- - **One line of config.** Add the plugin and every mock, resolver, and setup file is handled for you.
33
- - **Vitest-native speed.** Vitest runs on Vite's dev server -- no cold starts, native ESM, and fast HMR-driven watch mode.
34
- - **Comprehensive mocks.** 21 components and 25+ APIs are mocked out of the box, with full TypeScript types.
35
- - **Auto-detect presets.** The plugin scans your `node_modules` and automatically mocks third-party libraries like Reanimated, Gesture Handler, and Expo modules.
36
- - **Test helpers.** Switch platform, dimensions, and color scheme in a single function call -- no manual mock wiring.
41
+ - **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).
42
+ - **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.
43
+ - **No Jest config patchwork.** Add one plugin instead of custom transformers, `transformIgnorePatterns`, and brittle `jest.setup.js` mock files.
44
+ - **Auto-detect presets.** The plugin scans your `node_modules` and shadows native-runtime libraries (Reanimated, Gesture Handler, Safe Area, Navigation) automatically — under both engines.
45
+ - **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).
37
46
 
38
- If you are already using Vitest for your web projects, `vitest-native` lets you use the same tool, the same config patterns, and the same test runner for React Native.
47
+ > **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.
39
48
 
40
49
  ---
41
50
 
@@ -109,6 +118,7 @@ import { reactNative } from 'vitest-native';
109
118
  export default defineConfig({
110
119
  plugins: [
111
120
  reactNative({
121
+ engine: 'auto', // 'auto' | 'mock' | 'native' — auto → native when RN's babel deps are present, else mock
112
122
  platform: 'ios', // 'ios' | 'android' (default: 'ios')
113
123
  presets: [], // Preset[] -- omit for auto-detect
114
124
  mocks: {}, // Custom mock overrides for the react-native module
@@ -121,17 +131,58 @@ export default defineConfig({
121
131
 
122
132
  | Option | Type | Default | Description |
123
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. |
124
135
  | `platform` | `'ios' \| 'android'` | `'ios'` | Target platform. Controls `Platform.OS`, version defaults, and file extension resolution. |
125
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. |
126
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. |
127
138
  | `diagnostics` | `boolean` | `false` | Log plugin activity to the console for debugging. |
128
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. |
141
+
142
+ ### `engine`
143
+
144
+ Choose how React Native is provided to your tests:
145
+
146
+ - `'native'` — runs the **real** React Native JavaScript (component logic, prop
147
+ computation, validation, reconciliation), mocking only the native module boundary that
148
+ requires a device. Jest's `react-native` preset replaces many of these modules with
149
+ stubs, so the native engine exercises behavior Jest's mocks skip (see [Fidelity](#fidelity)
150
+ below). Best for components, integration, RNTL, virtualized lists, and anywhere a false
151
+ pass is costly. Requires `@react-native/babel-preset` and `@babel/core` (present by
152
+ default in React Native apps).
153
+ - `'mock'` — a lightweight, pure-JS reimplementation of React Native with **zero extra
154
+ dependencies**. Best for pure-logic/unit tests, maximum determinism, or when you can't
155
+ 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
157
+ `@react-native/babel-preset` and `@babel/core` are present (i.e. in any real RN app). It
158
+ falls back to `'mock'` only when those deps are absent, printing one line to explain why.
159
+ So `reactNative()` with no options runs real React Native. Set `engine: 'mock'` to opt out.
160
+
161
+ ```ts
162
+ reactNative({ engine: 'native' })
163
+ ```
164
+
165
+ #### Fidelity
166
+
167
+ Jest's `react-native` preset replaces many real modules with stubs, so behavior they
168
+ don't implement passes silently. The `native` engine runs the real implementations, so
169
+ those checks actually run. For example:
170
+
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 |
176
+
177
+ The `mock` engine is a simplification too, so it diverges from real RN the same way — reach
178
+ for `native` when a false pass would be costly. These specific differences are produced by
179
+ the cross-check/fidelity harnesses in the repository's `bench/` directory.
129
180
 
130
181
  ---
131
182
 
132
183
  ## Mocked Components and APIs
133
184
 
134
- The plugin provides a complete mock of the `react-native` module. Every component renders as a named host element (making snapshots readable), and every API function is a Vitest `vi.fn()` spy.
185
+ 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.
135
186
 
136
187
  ### Components (21)
137
188
 
@@ -179,6 +230,21 @@ The plugin provides a complete mock of the `react-native` module. Every componen
179
230
 
180
231
  ---
181
232
 
233
+ ## React Native Test Suite Conformance
234
+
235
+ 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:
236
+
237
+ - **Easing** — all 24 easing curve tests including sample data for quad, cubic, sin, exp, circle, and back
238
+ - **Bezier** — 9 cubic bezier mathematical property tests (symmetry, projection, boundary conditions)
239
+ - **flattenStyle** — 12 style merging tests covering override precedence, reference identity, and recursive flattening
240
+ - **processColor** — 9 color format conversion tests for named colors, RGB, RGBA, HSL, HSLA, and hex
241
+ - **Interpolation** — 12 numeric and string range mapping tests, including string output ranges (`deg`/`%`/arbitrary suffixes) and extrapolate modes (extend/clamp/identity)
242
+ - **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
+
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.
245
+
246
+ ---
247
+
182
248
  ## Test Helpers
183
249
 
184
250
  Import helpers from `vitest-native/helpers` to control mock state during tests.
@@ -188,6 +254,7 @@ import {
188
254
  setPlatform,
189
255
  setDimensions,
190
256
  setColorScheme,
257
+ setInsets,
191
258
  mockNativeModule,
192
259
  resetAllMocks,
193
260
  } from 'vitest-native/helpers';
@@ -235,6 +302,19 @@ test('renders dark mode styles', () => {
235
302
  });
236
303
  ```
237
304
 
305
+ ### `setInsets(insets)`
306
+
307
+ Update the safe area insets returned by `useSafeAreaInsets()` from `react-native-safe-area-context`. Requires the `safeAreaContext` preset to be active.
308
+
309
+ ```ts
310
+ import { setInsets } from 'vitest-native/helpers';
311
+
312
+ test('renders with no bottom inset (Android)', () => {
313
+ setInsets({ top: 24, bottom: 0 });
314
+ // useSafeAreaInsets() returns { top: 24, right: 0, bottom: 0, left: 0 }
315
+ });
316
+ ```
317
+
238
318
  ### `mockNativeModule(name, impl)`
239
319
 
240
320
  Register a custom native module mock. The module becomes available via `NativeModules[name]`.
@@ -254,7 +334,7 @@ test('uses a custom native module', () => {
254
334
 
255
335
  ### `resetAllMocks()`
256
336
 
257
- Reset all mocks to their default state. Restores platform to iOS, dimensions to iPhone 14 Pro defaults (390x844), color scheme to `'light'`, clears all mock call history, and undoes any `mockNativeModule` calls.
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.
258
338
 
259
339
  ```ts
260
340
  import { resetAllMocks } from 'vitest-native/helpers';
@@ -311,6 +391,112 @@ export default defineConfig({
311
391
  | `presets.screens()` | react-native-screens |
312
392
  | `presets.expo()` | Expo modules |
313
393
 
394
+ Presets apply under **both** engines: the mock engine and `engine: 'native'` (where they shadow each
395
+ library's native runtime — worklets, native modules — exactly as Jest does, while the surrounding tree
396
+ renders through real React Native).
397
+
398
+ ### Expo
399
+
400
+ The `expo` preset shadows the common Expo modules (`expo-constants`, `expo-status-bar`, `expo-font`,
401
+ `expo-asset`, `expo-splash-screen`, `expo-linking`) the way `jest-expo` mocks them. A component that
402
+ imports those renders under the native engine with no extra setup — there's a gated proof in
403
+ `tests-native/expo.test.tsx`. Two honest caveats:
404
+
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.
408
+ - **Expo SDK trails React Native.** Pin your `react-native` to the version your Expo SDK supports
409
+ (which is within this plugin's validated range), not the newest RN release.
410
+
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.
413
+
414
+ ---
415
+
416
+ ## Migrating from `vitest-react-native`
417
+
418
+ Used [`vitest-community/vitest-react-native`](https://github.com/vitest-community/vitest-react-native)
419
+ and it broke on a newer Vitest? `vitest-native` is the maintained continuation — same core
420
+ architecture (externalize RN, run its real JS under Node, mock only the native boundary). For the
421
+ common case it's a config swap:
422
+
423
+ ```diff
424
+ - import reactNative from 'vitest-react-native';
425
+ - import react from '@vitejs/plugin-react';
426
+ + import { reactNative } from 'vitest-native';
427
+ import { defineConfig } from 'vitest/config';
428
+
429
+ export default defineConfig({
430
+ - plugins: [reactNative(), react()],
431
+ + plugins: [reactNative()],
432
+ });
433
+ ```
434
+
435
+ Named import, and drop `@vitejs/plugin-react` (vitest-native handles the JSX runtime itself). The
436
+ full walkthrough — install, gotchas, what's the same — is in
437
+ **[docs/migrating-from-vitest-react-native.md](docs/migrating-from-vitest-react-native.md)**.
438
+
439
+ ---
440
+
441
+ ## Migrating from Jest
442
+
443
+ vitest-native ships a small compat layer that clears the mechanical Jest-API coupling in an existing
444
+ suite (the `jest` global, `@jest/globals`, jest-native's extend-expect):
445
+
446
+ ```ts
447
+ // vitest.config.mts
448
+ import { reactNative } from 'vitest-native';
449
+ import { jestCompatAliases, jestCompatSetup } from 'vitest-native/jest-compat';
450
+
451
+ export default defineConfig({
452
+ plugins: [reactNative({ engine: 'native' })],
453
+ resolve: { alias: { ...jestCompatAliases() } },
454
+ test: { globals: true, setupFiles: [jestCompatSetup] },
455
+ });
456
+ ```
457
+
458
+ This is **not** a turnkey drop-in — a real suite still needs a small per-suite cleanup (convert
459
+ top-level `jest.mock` → `vi.mock`, RNTL ≥ 12, re-record snapshots once with `-u`). The full recipe,
460
+ with a worked real-app example, is in **[docs/migrating-from-jest.md](docs/migrating-from-jest.md)**.
461
+
462
+ ---
463
+
464
+ ## Troubleshooting
465
+
466
+ **`@react-native/babel-preset not found — using the mock engine`**
467
+ You asked for the default (`auto`) engine but the native babel deps aren't installed, so it
468
+ fell back to the mock engine. To run real React Native, install them:
469
+
470
+ ```bash
471
+ npm i -D @react-native/babel-preset @babel/core
472
+ ```
473
+
474
+ To silence the notice and stay on mock deliberately, set `reactNative({ engine: 'mock' })`.
475
+
476
+ **`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,
478
+ so they load outside Vite's module graph — and Vitest's mocker only intercepts modules inside that
479
+ graph. Your **own** source modules mock normally; the gap is third-party RN-side packages. Options:
480
+
481
+ - Use a **[preset](#auto-detect-presets)** if one exists (it shadows the library the way Jest does).
482
+ - For a pure-JS library shipping untranspiled source, add it to the [`transform`](#plugin-options)
483
+ allowlist so the engine strips its Flow/TS as it loads.
484
+ - Or test that boundary on the **mock engine**, where `vi.mock` applies normally.
485
+
486
+ **`Unexpected token` / Flow syntax errors from a third-party library (native engine)**
487
+ The require hook strips Flow/TS from `react-native` and active presets, but not from arbitrary
488
+ packages. If a dependency ships untranspiled Flow/TS, add it to the
489
+ [`transform`](#plugin-options) allowlist.
490
+
491
+ **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.
495
+
496
+ **Snapshots differ after switching from Jest or the mock engine**
497
+ Real RN computes host props (e.g. `<Text>`'s `accessible`, `allowFontScaling`) that mocks omit, so
498
+ the tree is richer. Re-record once with `npx vitest -u` after migrating.
499
+
314
500
  ---
315
501
 
316
502
  ## RNTL Matchers
@@ -359,6 +545,77 @@ test('greeting is visible with correct style', () => {
359
545
 
360
546
  ---
361
547
 
548
+ ## Animated Matchers (Reanimated)
549
+
550
+ `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
+
552
+ | Matcher | Description |
553
+ |---|---|
554
+ | `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. |
556
+
557
+ Because the `reanimated` preset resolves `useAnimatedStyle`/`useAnimatedProps` synchronously, the animated values land on the rendered element and these matchers read straight from it:
558
+
559
+ ```tsx
560
+ import { render, screen } from '@testing-library/react-native';
561
+ import Animated, { useSharedValue, useAnimatedStyle } from 'react-native-reanimated';
562
+
563
+ function Skeleton({ visible }: { visible: boolean }) {
564
+ const opacity = useSharedValue(visible ? 1 : 0);
565
+ const style = useAnimatedStyle(() => ({ opacity: opacity.value }));
566
+ return <Animated.View testID="bone" style={style} />;
567
+ }
568
+
569
+ test('starts with full opacity', () => {
570
+ render(<Skeleton visible />);
571
+ expect(screen.getByTestId('bone')).toHaveAnimatedStyle({ opacity: 1 });
572
+ });
573
+ ```
574
+
575
+ ### Reanimated + Gesture Handler without manual mocks
576
+
577
+ Both libraries are auto-detected, so a component using a `Gesture` + `GestureDetector` driving an animated style needs no `vi.mock()` calls:
578
+
579
+ ```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';
583
+
584
+ function Card() {
585
+ const pressed = useSharedValue(false);
586
+ const style = useAnimatedStyle(() => ({ opacity: pressed.value ? 0.5 : 1 }));
587
+ const tap = Gesture.Tap().onStart(() => {
588
+ pressed.value = true;
589
+ });
590
+ return (
591
+ <GestureDetector gesture={tap}>
592
+ <Animated.View testID="card" style={style} />
593
+ </GestureDetector>
594
+ );
595
+ }
596
+
597
+ test('card renders at full opacity', () => {
598
+ render(<Card />);
599
+ expect(screen.getByTestId('card')).toHaveAnimatedStyle({ opacity: 1 });
600
+ });
601
+ ```
602
+
603
+ > 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.
604
+
605
+ ### TypeScript
606
+
607
+ To type the matchers on `expect()`, add the matcher types to your `tsconfig.json`:
608
+
609
+ ```jsonc
610
+ {
611
+ "compilerOptions": {
612
+ "types": ["vitest-native/matchers"]
613
+ }
614
+ }
615
+ ```
616
+
617
+ ---
618
+
362
619
  ## Snapshot Serializer
363
620
 
364
621
  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:
@@ -447,6 +704,8 @@ This prints details about which presets were detected, which modules are being m
447
704
  | `vite` | >= 5 |
448
705
  | `vitest` | >= 4 |
449
706
  | `node` | >= 20 |
707
+ | `react-native` (native engine) | 0.81–0.84 validated |
708
+ | `@react-native/babel-preset` (native engine) | `*` |
450
709
  | `@testing-library/react-native` (optional) | >= 12 |
451
710
 
452
711
  ---
@@ -0,0 +1,43 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __exportAll = (all, no_symbols) => {
9
+ let target = {};
10
+ for (var name in all) __defProp(target, name, {
11
+ get: all[name],
12
+ enumerable: true
13
+ });
14
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
15
+ return target;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
19
+ key = keys[i];
20
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
21
+ get: ((k) => from[k]).bind(null, key),
22
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
23
+ });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
28
+ value: mod,
29
+ enumerable: true
30
+ }) : target, mod));
31
+ //#endregion
32
+ Object.defineProperty(exports, "__exportAll", {
33
+ enumerable: true,
34
+ get: function() {
35
+ return __exportAll;
36
+ }
37
+ });
38
+ Object.defineProperty(exports, "__toESM", {
39
+ enumerable: true,
40
+ get: function() {
41
+ return __toESM;
42
+ }
43
+ });
package/dist/helpers.cjs CHANGED
@@ -35,6 +35,10 @@ function setColorScheme(scheme) {
35
35
  mock.Appearance.setColorScheme(resolved);
36
36
  if (mock.useColorScheme._setScheme) mock.useColorScheme._setScheme(resolved);
37
37
  }
38
+ function setInsets(insets) {
39
+ const safeArea = globalThis.__vitest_native_preset_mocks?.["react-native-safe-area-context"];
40
+ if (safeArea?._setInsets) safeArea._setInsets(insets);
41
+ }
38
42
  function mockNativeModule(name, impl) {
39
43
  const mock = getMock();
40
44
  if (originalNativeModules === null) originalNativeModules = mock.NativeModules;
@@ -104,10 +108,16 @@ function resetAllMocks() {
104
108
  mock.NativeModules = originalNativeModules;
105
109
  originalNativeModules = null;
106
110
  }
111
+ const presetMocks = globalThis.__vitest_native_preset_mocks;
112
+ if (presetMocks) for (const mod of Object.values(presetMocks)) {
113
+ if (mod?._reset) mod._reset();
114
+ if (mod?._resetStore) mod._resetStore();
115
+ }
107
116
  }
108
117
  //#endregion
109
118
  exports.mockNativeModule = mockNativeModule;
110
119
  exports.resetAllMocks = resetAllMocks;
111
120
  exports.setColorScheme = setColorScheme;
112
121
  exports.setDimensions = setDimensions;
122
+ exports.setInsets = setInsets;
113
123
  exports.setPlatform = setPlatform;
@@ -13,7 +13,13 @@ declare function setDimensions(dims: {
13
13
  fontScale?: number;
14
14
  }): void;
15
15
  declare function setColorScheme(scheme: "light" | "dark" | null): void;
16
+ declare function setInsets(insets: {
17
+ top?: number;
18
+ right?: number;
19
+ bottom?: number;
20
+ left?: number;
21
+ }): void;
16
22
  declare function mockNativeModule(name: string, impl: Record<string, any>): void;
17
23
  declare function resetAllMocks(): void;
18
24
  //#endregion
19
- export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setPlatform };
25
+ export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };
@@ -13,7 +13,13 @@ declare function setDimensions(dims: {
13
13
  fontScale?: number;
14
14
  }): void;
15
15
  declare function setColorScheme(scheme: "light" | "dark" | null): void;
16
+ declare function setInsets(insets: {
17
+ top?: number;
18
+ right?: number;
19
+ bottom?: number;
20
+ left?: number;
21
+ }): void;
16
22
  declare function mockNativeModule(name: string, impl: Record<string, any>): void;
17
23
  declare function resetAllMocks(): void;
18
24
  //#endregion
19
- export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setPlatform };
25
+ export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };
package/dist/helpers.mjs CHANGED
@@ -34,6 +34,10 @@ function setColorScheme(scheme) {
34
34
  mock.Appearance.setColorScheme(resolved);
35
35
  if (mock.useColorScheme._setScheme) mock.useColorScheme._setScheme(resolved);
36
36
  }
37
+ function setInsets(insets) {
38
+ const safeArea = globalThis.__vitest_native_preset_mocks?.["react-native-safe-area-context"];
39
+ if (safeArea?._setInsets) safeArea._setInsets(insets);
40
+ }
37
41
  function mockNativeModule(name, impl) {
38
42
  const mock = getMock();
39
43
  if (originalNativeModules === null) originalNativeModules = mock.NativeModules;
@@ -103,6 +107,11 @@ function resetAllMocks() {
103
107
  mock.NativeModules = originalNativeModules;
104
108
  originalNativeModules = null;
105
109
  }
110
+ const presetMocks = globalThis.__vitest_native_preset_mocks;
111
+ if (presetMocks) for (const mod of Object.values(presetMocks)) {
112
+ if (mod?._reset) mod._reset();
113
+ if (mod?._resetStore) mod._resetStore();
114
+ }
106
115
  }
107
116
  //#endregion
108
- export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setPlatform };
117
+ export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };