Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/library-test-support.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"vitest-native": minor
---

Under the native engine, React Native libraries' own Jest support runs with Jest's module semantics. A library's setup file or mock (`react-native-gesture-handler/jestSetup`, `react-native-safe-area-context/jest/mock`, `react-native-reanimated/mock`) gets a `jest` of its own: `jest.mock` reaches every `require` of the module, `jest.requireActual` and `@jest/globals` work, and an implementation the library installs while building its mocks survives `vi.resetAllMocks()` and `mockReset: true` (where Jest's `resetMocks` would drop it). What a library's setup registers lasts as long as its module: each test file loads it afresh by default and under the hot runtime, and under `isolate: false` a setup file's library mocks reach every file, as the module itself does. A setup file is served whether it is required, imported or listed in `setupFiles`, and so is one of a workspace library linked from outside node_modules; the project's own files named `mock` or under a `jest/` directory are not given a library's `jest`. Before, a suite migrated from Jest that imported such a setup file ran it with Vitest's `vi`, whose `mock` never reaches Node's `require`, so it changed nothing. Nothing is put on the global `jest`.

`jest.requireActual` of a package a preset shadows is the package, as under Jest; it was the preset.

Under the native engine, these presets are their library's own mock, as a Jest suite installs it, matching Jest on every probe of an Expo SDK 58 app but the one noted:

- `react-native-worklets` is Worklets' `lib/module/mock.js`. The real package's JS implementation fails every test file with react-native-gesture-handler 3 ("`getUIRuntimeHolder` is not supported on web"), under Jest as well. `runOnJS`, `runOnUI`, `scheduleOnRN` and `scheduleOnUI` behave as under Jest with that mock; the preset ran them synchronously.
- `react-native-safe-area-context` is its `jest/mock`: insets are zero on a 320×640 frame (the preset gave 47/34 on 390×844) unless `<SafeAreaProvider initialMetrics>` gives metrics, which the preset ignored, and `useSafeAreaInsets` and `useSafeAreaFrame` are mock functions. `setInsets()` now sets what `useSafeAreaInsets` returns, until `resetAllMocks()`, and no longer reaches `SafeAreaInsetsContext`, `withSafeAreaInsets` or `initialWindowMetrics`; `<SafeAreaProvider initialMetrics>` gives every consumer the same insets. A suite's own `jest.mock('react-native-safe-area-context', () => ({ ...jest.requireActual('react-native-safe-area-context'), ... }))` now spreads the real package, as under Jest, whose `SafeAreaProvider` renders nothing until native metrics arrive.
- `react-native-keyboard-controller`, `@gorhom/bottom-sheet` and `@react-native-community/netinfo` are their own Jest mocks (`jest`, `mock`, `jest/netinfo-mock.js`): keyboard-controller's hooks return React Native `Animated.Value`s and are mock functions, bottom-sheet's views render their children and nothing of their own (a `BottomSheetView`'s `testID` is not on the tree), and netinfo rests on a connected cellular network, each as under Jest. One difference is deliberate: bottom-sheet's default import is its `BottomSheet` component, where Jest's interop hands a suite the mock's whole module object, which does not render.

`react-native-gesture-handler` and `@shopify/flash-list` run as themselves under the native engine, with the Jest setup file each ships (`jestSetup.js`) run before the project's setup files, as a Jest suite lists them in `setupFiles`. The presets replaced the whole package: gesture-handler 3's hook API (`usePanGesture` and the rest), builder methods such as `onBegin` and `activeOffsetX`, and its own test helpers were missing. Now its native module and host components are its own mocks, a `Pressable` press fires `onPress`, and a `FlashList` renders a window of rows over the layout its setup measures (10 rows, then 15 once it fills in, as under Jest), where the preset rendered every row. `react-native-gesture-handler/Swipeable` and the other modules the preset made up for gesture-handler 3, which does not ship them, no longer resolve, as under Jest. `presets: { gestureHandler: true }` or `{ flashList: true }` keeps a preset.

A package naming different files in its `react-native` field and its `main` is one module whether imported or required: a bare `require` now resolves the `react-native` field, as Metro and an `import` do, where it read `main` and loaded a second copy (`react-native-worklets` was loaded twice). With Reanimated 4.7 or later, its test helpers `withReanimatedTimer` and `advanceAnimationByTime` work without the jest-compat layer.
4 changes: 1 addition & 3 deletions .changeset/reanimated-own-mock.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@

Under the native engine, with Reanimated 4.7 or later, `react-native-reanimated` is Reanimated's own test mock (`react-native-reanimated/mock`), as a Jest suite gets it with `jest.mock('react-native-reanimated', () => require('react-native-reanimated/mock'))`. The hand-written preset lacked 104 of the names that mock provides (`interpolateColor`, `clamp`, `Keyframe`, `useScrollOffset`, `Extrapolate`, most layout animation presets, `Easing.exp`/`bounce`/`elastic`, and its test helpers `withReanimatedTimer` and `getAnimatedStyle`), and called animation callbacks with `{ finished, current }` where Reanimated passes `true`, so `if (finished)` code paths did not run as on a device. On an Expo SDK 58 app, every probe of reanimated matches Jest with Reanimated's mock except `Animated.View`'s shape, which wraps real React Native's `View`.

The mock loads the real package and `react-native-worklets` in their JS implementations, through the Jest resolvers both libraries ship (from Reanimated 4.7 and Worklets 0.9), which the native engine now applies to their files. With an older Reanimated or Worklets, and under the mock engine, the existing presets stay.
The mock loads the real package in its JS implementation, through the Jest resolvers Reanimated and Worklets ship (from Reanimated 4.7 and Worklets 0.9), which the native engine now applies to their files. With an older Reanimated or Worklets, and under the mock engine, the existing preset stays.

What a suite on the preset sees change, each as under Jest with Reanimated's mock:

- A `useSharedValue` is a new `{ value }` on every render, so a value set before a re-render does not survive it; `makeMutable(x)` returns `x`, and `useAnimatedKeyboard()` returns plain numbers.
- `cancelAnimation`, `scrollTo` and the other no-op functions are plain functions, not `vi.fn`, so `toHaveBeenCalled` on them fails.
- `withReanimatedTimer` and `advanceAnimationByTime` use Jest's fake timers and need the jest-compat layer (`jestCompatSetup`).
- Under the native engine the worklets preset no longer applies with Worklets 0.9 or later: `runOnJS`, `runOnUI`, `scheduleOnRN` and `scheduleOnUI` run their worklet on a later tick, as the real package does under Jest, where the preset ran it synchronously, so a test that reads the result awaits it (`await waitFor(...)`). `presets: { worklets: true }` keeps the preset.

A file that imports reanimated now loads the real package beneath the mock, about 75–125 ms more per file (measured on 24 such files, hot runtime and stock). `presets: { reanimated: false }` turns the preset off; the real package then loads in its JS implementation, but hooks such as `useAnimatedStyle` need the worklets Babel plugin, which the engine does not apply to app code.
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,22 +235,22 @@ export default defineConfig({
| Preset | Library | What's mocked |
|--------|---------|---------------|
| `presets.reanimated()` | `react-native-reanimated` | Native engine with Reanimated 4.7+: Reanimated's own test mock (`react-native-reanimated/mock`), its whole API for the installed version, over the real package in its JS implementation, as a Jest suite gets it. Mock engine, or an older Reanimated: `useSharedValue`, `useAnimatedStyle`, `withTiming`, `withSpring`, `withDelay`, `withSequence`, `withRepeat`, layout animations (`FadeIn`, `FadeOut`, `SlideInRight`), `Easing`, `interpolate`, `createAnimatedComponent` |
| `presets.worklets()` | `react-native-worklets` | Native engine with Worklets 0.9+: none needed, the real package runs in its JS implementation, so `runOnJS`, `runOnUI`, `scheduleOnRN` and `scheduleOnUI` run their worklet on a later tick, as under Jest. Mock engine, or an older Worklets: they run synchronously on the JS thread |
| `presets.gestureHandler()` | `react-native-gesture-handler` | `GestureHandlerRootView`, gesture handlers (Pan, Tap, LongPress, Pinch, Rotation, Fling), `Gesture` API (v2), `GestureDetector`, `Swipeable`, touchable wrappers, state constants |
| `presets.safeAreaContext()` | `react-native-safe-area-context` | `SafeAreaProvider`, `SafeAreaView`, `useSafeAreaInsets`, `useSafeAreaFrame`, `initialWindowMetrics`, `withSafeAreaInsets` |
| `presets.worklets()` | `react-native-worklets` | Native engine: Worklets' own test mock (`lib/module/mock.js`), as a Jest suite installs it, so `runOnJS`, `runOnUI`, `scheduleOnRN` and `scheduleOnUI` behave as under Jest. Mock engine, or a Worklets without that mock: they run synchronously on the JS thread |
| `presets.gestureHandler()` | `react-native-gesture-handler` | Native engine: none needed, the real package runs with its own `jestSetup.js` mocking its native module and host components, as a Jest suite lists it (gesture-handler 3's hook API, the whole builder API). Mock engine: `GestureHandlerRootView`, gesture handlers (Pan, Tap, LongPress, Pinch, Rotation, Fling), `Gesture` API (v2), `GestureDetector`, `Swipeable`, touchable wrappers, state constants |
| `presets.safeAreaContext()` | `react-native-safe-area-context` | Native engine: safe-area-context's own test mock (`jest/mock`), as a Jest suite installs it: zero insets on a 320x640 frame unless `<SafeAreaProvider initialMetrics>` gives metrics, with `useSafeAreaInsets`/`useSafeAreaFrame` as mock functions. Mock engine: `SafeAreaProvider`, `SafeAreaView`, `useSafeAreaInsets`, `useSafeAreaFrame`, `initialWindowMetrics`, `withSafeAreaInsets` |
| `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 |
| `presets.screens()` | `react-native-screens` | `enableScreens`, `Screen`, `ScreenContainer`, `ScreenStack` |
| `presets.asyncStorage()` | `@react-native-async-storage/async-storage` | in-memory store (`getItem`/`setItem`/`multiGet`/`mergeItem`/…) |
| `presets.expo()` | `expo-constants`, `expo-font`, `expo-asset`, `expo-splash-screen`, `expo-linking`, `expo-status-bar` | constants, fonts, assets, splash screen, linking, status bar |
| `presets.deviceInfo()` | `react-native-device-info` | string/bool/number getters with sync + async variants |
| `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 |
| `presets.netInfo()` | `@react-native-community/netinfo` | connected-wifi state, `fetch`/`refresh`/`addEventListener`/`useNetInfo`, state-type enums |
| `presets.netInfo()` | `@react-native-community/netinfo` | Native engine: netinfo's own test mock (`jest/netinfo-mock.js`), as a Jest suite installs it: a connected cellular network. Mock engine: connected-wifi state, `fetch`/`refresh`/`addEventListener`/`useNetInfo`, state-type enums |
| `presets.svg()` | `react-native-svg` | `Svg`, `Path`, `Circle`, `Rect`, `G`, … as host components |
| `presets.webview()` | `react-native-webview` | `WebView` (default + named) host component |
| `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`) |
| `presets.flashList()` | `@shopify/flash-list` | `FlashList` rendering its data through `renderItem`, the ref surface, v2 recycler hooks |
| `presets.bottomSheet()` | `@gorhom/bottom-sheet` | `BottomSheet`, `BottomSheetModal` + provider, sheet views, scroll/list variants, `BottomSheetTextInput`, backdrop, footer |
| `presets.keyboardController()` | `react-native-keyboard-controller` | `KeyboardProvider`, `KeyboardAvoidingView`, `KeyboardAwareScrollView`, `KeyboardStickyView`, `KeyboardToolbar`; the imperative `KeyboardController` is inert |
| `presets.flashList()` | `@shopify/flash-list` | Native engine: none needed, the real list runs with its own `jestSetup.js` measuring its layout, as a Jest suite lists it. Mock engine: `FlashList` rendering its data through `renderItem`, the ref surface, v2 recycler hooks |
| `presets.bottomSheet()` | `@gorhom/bottom-sheet` | Native engine: bottom-sheet's own test mock (`@gorhom/bottom-sheet/mock`), as a Jest suite installs it. Mock engine: `BottomSheet`, `BottomSheetModal` + provider, sheet views, scroll/list variants, `BottomSheetTextInput`, backdrop, footer |
| `presets.keyboardController()` | `react-native-keyboard-controller` | Native engine: keyboard-controller's own test mock (`react-native-keyboard-controller/jest`), as a Jest suite installs it. Mock engine: `KeyboardProvider`, `KeyboardAvoidingView`, `KeyboardAwareScrollView`, `KeyboardStickyView`, `KeyboardToolbar`; the imperative `KeyboardController` is inert |
| `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 |
| `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 |

Expand Down
6 changes: 6 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading