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