From ecd4ecf28cbdb9d12f7c22c268652a504e3e68d9 Mon Sep 17 00:00:00 2001 From: Daniel Fry <95628792+danfry1@users.noreply.github.com> Date: Wed, 28 Oct 2026 22:40:09 +0000 Subject: [PATCH 1/4] feat(native): a library's own Jest support runs with Jest's semantics Libraries ship their test support for Jest: setup files that call jest.mock for their native modules, and mocks that call jest.fn or import @jest/globals. Under Vitest such a file got vi, whose mock never reaches Node's require, so it changed nothing. Each support file now gets a jest of its own that registers in the Node-side registry, and jest.requireActual of a package a preset shadows is the package. --- .changeset/library-test-support.md | 7 + bun.lock | 3 + .../vitest-native/docs/preset-architecture.md | 187 +++++++++++ packages/vitest-native/package.json | 1 + .../src/jest-compat/node-registry.mjs | 46 ++- .../vitest-native/src/jest-compat/setup.mjs | 2 +- packages/vitest-native/src/native/hooks.mjs | 6 + .../vitest-native/src/native/library-jest.mjs | 291 ++++++++++++++++++ packages/vitest-native/src/native/setup.mjs | 7 + .../project-own-support/src/api/mock.cjs | 2 + .../vn-lib-jest-support/NativeThing.js | 8 + .../fixtures/vn-lib-jest-support/index.js | 5 + .../vn-lib-jest-support/jest/commented.js | 4 + .../vn-lib-jest-support/jest/esm-min.js | 3 + .../fixtures/vn-lib-jest-support/jest/esm.js | 2 + .../fixtures/vn-lib-jest-support/jest/mock.js | 5 + .../fixtures/vn-lib-jest-support/jestSetup.js | 5 + .../fixtures/vn-lib-jest-support/package.json | 6 + .../tests-native/fixtures/vn-ws-lib/index.js | 3 + .../fixtures/vn-ws-lib/jestSetup.js | 1 + .../tests-native/fixtures/vn-ws-lib/native.js | 3 + .../fixtures/vn-ws-lib/package.json | 6 + .../c1-library-setup.test.ts | 8 + .../c2-library-setup.test.ts | 8 + .../jest-registry-no-isolate/library-setup.ts | 3 + .../jest-registry-require-actual.test.ts | 15 + .../tests-native/library-jest-import.test.ts | 13 + .../tests-native/library-jest.test.ts | 91 ++++++ ...vitest.jest-registry-no-isolate.config.mts | 8 +- 29 files changed, 738 insertions(+), 11 deletions(-) create mode 100644 .changeset/library-test-support.md create mode 100644 packages/vitest-native/docs/preset-architecture.md create mode 100644 packages/vitest-native/src/native/library-jest.mjs create mode 100644 packages/vitest-native/tests-native/fixtures/project-own-support/src/api/mock.cjs create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/NativeThing.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/index.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/commented.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/esm-min.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/esm.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/mock.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jestSetup.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/package.json create mode 100644 packages/vitest-native/tests-native/fixtures/vn-ws-lib/index.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-ws-lib/jestSetup.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-ws-lib/native.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-ws-lib/package.json create mode 100644 packages/vitest-native/tests-native/jest-registry-no-isolate/c1-library-setup.test.ts create mode 100644 packages/vitest-native/tests-native/jest-registry-no-isolate/c2-library-setup.test.ts create mode 100644 packages/vitest-native/tests-native/jest-registry-no-isolate/library-setup.ts create mode 100644 packages/vitest-native/tests-native/library-jest-import.test.ts create mode 100644 packages/vitest-native/tests-native/library-jest.test.ts diff --git a/.changeset/library-test-support.md b/.changeset/library-test-support.md new file mode 100644 index 000000000..a97eddbbb --- /dev/null +++ b/.changeset/library-test-support.md @@ -0,0 +1,7 @@ +--- +"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. diff --git a/bun.lock b/bun.lock index 959bdb7ed..cd36e35e3 100644 --- a/bun.lock +++ b/bun.lock @@ -92,6 +92,7 @@ "untranspiled-jsx-lib": "file:./tests-native/fixtures/untranspiled-jsx-lib", "vite": "^8.3.4", "vitest": "5.0.5", + "vn-lib-jest-support": "file:./tests-native/fixtures/vn-lib-jest-support", }, "peerDependencies": { "@babel/core": "*", @@ -1982,6 +1983,8 @@ "vitest-native/untranspiled-jsx-lib": ["untranspiled-jsx-lib@file:packages/vitest-native/tests-native/fixtures/untranspiled-jsx-lib", {}], + "vitest-native/vn-lib-jest-support": ["vn-lib-jest-support@file:packages/vitest-native/tests-native/fixtures/vn-lib-jest-support", {}], + "wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], "xml2js/xmlbuilder": ["xmlbuilder@11.0.1", "", {}, "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA=="], diff --git a/packages/vitest-native/docs/preset-architecture.md b/packages/vitest-native/docs/preset-architecture.md new file mode 100644 index 000000000..1f0f24bfa --- /dev/null +++ b/packages/vitest-native/docs/preset-architecture.md @@ -0,0 +1,187 @@ +# Presets that use a library's own test support + +Status: proposal (2026-10-27), revised after an adversarial review (see "What the review changed"). + +## The problem + +A preset stands in for a React Native library a test cannot run as it is. The built-in +presets were written by hand, and a hand-written stand-in drifts: measured against each +library's own Jest mock, reanimated's preset lacked 104 names, gesture-handler's 36, +safe-area-context's 4, and several returned values the library never gives +(`tests/preset-library-mocks.test.ts` lists every gap). + +Almost every one of these libraries already ships its own test support, which a Jest +suite wires up by hand: + +| Library | What it ships for Jest | What it replaces | +|---|---|---| +| react-native-reanimated (4.7+) | `react-native-reanimated/mock`, `jest/resolver.js` | the package, with its own mock over the real JS | +| react-native-worklets (0.9+) | `jest/resolver.js` | nothing: the JS implementation runs | +| react-native-gesture-handler | `jestSetup.js` | its native module and host components; the JS is real | +| @shopify/flash-list | `jestSetup.js` | layout measurement; the list is real | +| react-native-safe-area-context | `jest/mock` | its hooks and provider, over the real package | +| expo-* modules | `mocks/.ts` (generated), jest-expo's table | their native modules; the JS is real | + +Three of these are already used, each by code written for that one library: Expo +modules' own mocks (#323), reanimated's mock and the two resolvers (#336). Each new +library would be another special case in the engine, and a user with a library of +their own has no way to do the same. + +## The proposal + +A preset declares, per package, which kind of test support the library ships, and the +engine handles each kind once. The hand-written `factory` stays, for the mock engine +and for libraries that ship nothing. + +```ts +export default definePreset({ + name: "gestureHandler", + modules: { + "react-native-gesture-handler": { + // Under the native engine: the real package, with the library's own setup file + // run first (its jest.mock calls replace the native module and host components). + native: { setupFiles: ["react-native-gesture-handler/jestSetup.js"] }, + // Under the mock engine, or where `native` cannot apply: + exports: [...], + factory: () => ({ ... }), + }, + }, +}); +``` + +The `native` field takes one of three forms: + +- `{ mock: "/mock" }`: the package is the library's mock module, as + `jest.mock(pkg, () => require(mock))` makes it. Export names are read from the mock + file (`mockModuleExportNames`). Reanimated, safe-area-context. +- `{ setupFiles: [...] }`: the package runs as itself, after the library's setup files. + Gesture-handler, flash-list. +- `{ asItself: true }`: the package runs as itself with nothing more. Worklets. + +Alongside `native`: + +- `jestResolver: "/jest/resolver"`: the library's resolver, applied to requests + from its files (`native/jest-resolvers.mjs`, today a fixed list of two). +- `requires: { "": ">=4.7", ... }`: the versions the library's test support + needs. Outside them, the `factory` serves, as for reanimated before 4.7 today. + +Libraries' test support is written for Jest: setup files call `jest.mock`, and mocks +import `@jest/globals` (safe-area-context's) or call `jest.fn`. The engine runs them with +jest-compat's `jest` and its `@jest/globals`, whether or not the suite itself uses +jest-compat, the way it already serves Expo modules' generated mocks. + +Each kind is one piece of engine code, tested once: the mock redirect, running a +library's setup files before the user's, the resolver bridge, the version gate. A +built-in preset becomes a short declaration, and so does a user's. + +## Speed + +Loading the real package beneath a library's mock costs about 80 ms per test file for +reanimated, 43% of it module resolution (778 resolves for 337 modules). The precompiled +registry (`native/registry.mjs`) already removes exactly that for React Native: its +graph is compiled once into lazy factories with every require resolved ahead of time, +which took a typical file from 59 ms to 14 ms. A package a preset declares with +`native` has its graph inlined into the registry the same way, resolved through its +`jestResolver`, so the cost of a library's own test support is paid once per build, +not per file. The registry's invariants hold as they do for React Native: one instance +per module across the registry boundary, lazy factories, and the hot worker's preload +order. + +## Users' own presets + +A user preset is the same declaration. For a library that ships a Jest mock: + +```ts +// test/presets/my-lib.ts +import { definePreset } from "vitest-native/presets"; +export default definePreset({ + name: "myLib", + modules: { "my-lib": { native: { mock: "my-lib/jest/mock" } } }, +}); +``` + +`definePreset` checks the declaration's shape at load and types it. The mock engine +needs a `factory` as before; under the native engine the declaration alone is enough. +The drift gate (`tests/preset-library-mocks.test.ts`) is available for any preset that +names a library mock. + +## What the review changed + +Probing the installed libraries under the native engine found the direction sound and the +mechanism above incomplete: + +- **jest-compat's `jest` does not reach a library's files.** At runtime `jest.mock` is + `vi.mock`, which never reaches Node's `require`, and `jestMockTransform` does not run on + node_modules. A library setup file has to be given a `jest` scoped to that file, whose + `mock(spec, factory)` registers in the Node-side registry keyed from the file + (`jest-compat/node-registry.mjs`); with that, gesture-handler's `jestSetup.js` renders the + real gesture-handler over real React Native, and a press fires `onPress`. The same gap + means a migrated suite's `import 'react-native-gesture-handler/jestSetup'` does nothing + today. The scoped `jest` is passed to library code only, never as `globalThis.jest`: + RNTL and other code read `typeof jest` to choose their behaviour. +- **A package that runs as itself loads twice.** `import` resolves through the package's + `react-native` field (`src/`) and `require` through `main` (`lib/`), so a context created + by one copy is not the other's: safe-area's hooks, required by a Node-owned library, + threw "No safe area value available" under a provider the test imported. A package that + runs as itself needs one entry for both graphs. As built, a bare require of a package + with a `react-native` field (and no `exports`) resolves that field: the file Vite's + import and Metro resolve, and the build libraries' own Jest setup targets + (gesture-handler's mocks `./src/...`). tests-native/one-instance-per-package.test.ts + holds it. `{ mock }` packages are shadowed by name in both graphs and do not have this. +- **`{ mock }` needs three engine pieces** for safe-area-context: `@jest/globals` for + requests from declared packages' files on the Node side; a `requireActual` that bypasses + a preset's name shadow (today `jest.requireActual('react-native-safe-area-context')` + returns the preset); and an export selector, since that mock's module is its `default`. + Expo's generated mocks are plain data and never needed any of this. +- **Worklets ships a mock, and gesture-handler needs it.** Gesture-handler's + reanimated wrapper calls `getUIRuntimeHolder()`, which worklets' JS implementation throws + for in a microtask, failing every file. Worklets on its own `mock.js` fixes it, and + reanimated's mock still works over it. Libraries' support combines across packages. +- **Library mocks keep their implementations through a reset.** A mock built with `jest.fn().mockImplementation()` + loses its implementation on `vi.resetAllMocks()` / `mockReset: true`, as Jest's + `resetMocks` would drop it, which would break a guarantee the presets give (#278/#287). The scoped `jest.fn` + takes the implementation a library mock installs while it is built as the mock's reset + baseline, and the reset gate covers library mocks. +- **Speed: Jest parity, not free.** Evaluation stays per file (about 30 ms each for + reanimated's mock and gesture-handler, 12 ms for flash-list, with resolution warm), + because their graphs evaluate eagerly. Registry inlining would remove resolution, but + needs ESM-to-CommonJS compilation of these packages, the library resolvers in its walk, + name-shadowed requires preserved, an ESM facade per package and its versions in the + cache key; it is measured before it is built, last. +- **Gate on files, not versions.** Only reanimated and worklets need a gate (their + resolvers appear in 4.7 and 0.9), probed by file from the right directory (worklets from + reanimated's); a native-engine fallback to the hand-written factory is reported once, + and by `doctor`. +- **Internal first.** The declaration combines forms per package and across packages, so + its shape is settled on the built-in presets before any of it is public. The public + surface may end up being "the library's Jest setup or mock lines, with Jest semantics". + +## Limits found while building + +- A library's `jest.mock` reaches a module through Node's CommonJS loader. A package + that runs as a native ES module (one vitest-native does not compile, such as a package + the project does not declare) imports its modules past it, so a setup file's mocks do + not apply there. + +## Order of work + +1. **The Jest-semantics primitive** for library code: a scoped `jest` (`mock`, + `requireActual` that bypasses shadows, `fn` whose built implementation is the reset + baseline), file-keyed Node registration, and `@jest/globals` for declared packages. + It also makes a migrated suite's own library setup imports work. +2. **One entry for both graphs** for packages that run as themselves, with a gate. +3. **The `{ mock }` libraries**: worklets, safe-area-context, keyboard-controller, + bottom-sheet, netinfo (reanimated is done), each measured against Jest with the + library's own mock, and the drift gate's lists emptied as they move. +4. **gesture-handler and flash-list** on their setup files, tested together with + reanimated and worklets, measured against Jest. +5. **Registry inlining**, only if the 24-file benchmark shows it is worth the work above. +6. Docs: the preset guide's "Your own presets" section, once the shape is public. + +## Not proposed + +- Discovering a library's test support automatically: whether a mock applies is the + library's documented choice, and guessing it from file names would serve a mock a + library did not intend for this. +- Running the libraries' setup files under the mock engine: it has no real React Native + for the real packages to run on. diff --git a/packages/vitest-native/package.json b/packages/vitest-native/package.json index fa1d2107a..12b97db2d 100644 --- a/packages/vitest-native/package.json +++ b/packages/vitest-native/package.json @@ -173,6 +173,7 @@ "rn-condition-cjs-lib": "file:./tests-native/fixtures/rn-condition-cjs-lib", "rn-condition-lib": "file:./tests-native/fixtures/rn-condition-lib", "rn-ecosystem-lib": "file:./tests-native/fixtures/rn-ecosystem-lib", + "vn-lib-jest-support": "file:./tests-native/fixtures/vn-lib-jest-support", "rn-mainfield-lib": "file:./tests-native/fixtures/rn-mainfield-lib", "rn-platform-flow-lib": "file:./tests-native/fixtures/rn-platform-flow-lib", "rn-singleton-lib": "file:./tests-native/fixtures/rn-singleton-lib", diff --git a/packages/vitest-native/src/jest-compat/node-registry.mjs b/packages/vitest-native/src/jest-compat/node-registry.mjs index f4bc5670c..74b062c1b 100644 --- a/packages/vitest-native/src/jest-compat/node-registry.mjs +++ b/packages/vitest-native/src/jest-compat/node-registry.mjs @@ -188,9 +188,20 @@ function createState() { return filename !== null ? state.entries.get(filename) : state.unresolved.get(request); }; - state.register = (from, spec, factory) => { + // `library`: registered by a library's own test support (native/library-jest.mjs), + // whose lifetime the native setup decides at each file boundary; `owner` is what it + // keeps it by. + state.register = (from, spec, factory, { library = false, owner = null } = {}) => { const filename = state.resolveFrom(spec, from); - const entry = { spec, factory, has: false, value: undefined, evaluating: false }; + const entry = { + spec, + factory, + has: false, + value: undefined, + evaluating: false, + library, + owner, + }; if (filename !== null) state.entries.set(filename, entry); else state.unresolved.set(spec, entry); // The hoisted `vi.mock` factory looks its entry up by where it was written. @@ -212,7 +223,12 @@ function createState() { const isPath = spec.startsWith(".") || path.isAbsolute(spec); const anchor = isPath && caller ? caller : rootFile; const filename = state.resolveFrom(spec, anchor); - if (actual) state.bypass = filename ?? `\0${spec}`; + if (actual) { + state.bypass = filename ?? `\0${spec}`; + // A preset shadows its package by name (native/hooks.mjs); the actual module is + // the package, as Jest's requireActual gives it, so this one load skips it too. + if (!isPath) globalThis.__vitest_native_preset_actual = spec; + } try { const load = createRequire(anchor); if (filename !== null && (isPath || expandAlias(spec, config.aliases) !== spec)) { @@ -232,7 +248,10 @@ function createState() { } throw error; } finally { - if (actual) state.bypass = null; + if (actual) { + state.bypass = null; + globalThis.__vitest_native_preset_actual = undefined; + } } }; @@ -316,10 +335,21 @@ function createState() { }; }; - state.clear = () => { - state.entries.clear(); - state.unresolved.clear(); - state.byCall.clear(); + /** + * Drop the registrations. The compat setup clears the test file's own before each + * file (`keepLibrary`): libraries' registrations were settled already, by the native + * setup, which runs first and keeps those `keep` says. The hot runtime clears + * everything at the file boundary, before the setup files run again. + */ + state.clear = ({ keepLibrary = false, keep: kept } = {}) => { + const keep = (map) => { + for (const [key, entry] of map) { + if (!((keepLibrary && entry.library) || kept?.(entry))) map.delete(key); + } + }; + keep(state.entries); + keep(state.unresolved); + keep(state.byCall); state.bypass = null; state.isolation = null; }; diff --git a/packages/vitest-native/src/jest-compat/setup.mjs b/packages/vitest-native/src/jest-compat/setup.mjs index fba9ab5f7..e2df28b8c 100644 --- a/packages/vitest-native/src/jest-compat/setup.mjs +++ b/packages/vitest-native/src/jest-compat/setup.mjs @@ -243,7 +243,7 @@ if (typeof globalThis.__vnInteropMock !== "function") globalThis.__vnInteropMock // file, so a worker reused without the hot runtime (`isolate: false`, or a watch // rerun of the same file) starts each one empty here. The hot runtime clears them at // the file boundary instead, through its state manifest, which verifies it did. - if (!globalThis.__vitest_native_hot_reset) registry.clear(); + if (!globalThis.__vitest_native_hot_reset) registry.clear({ keepLibrary: true }); // Hot runtime: cleared at the file boundary and verified empty (state-manifest.mjs). globalThis.__vitest_native_register_state?.({ id: NODE_MOCKS_STATE_ID, diff --git a/packages/vitest-native/src/native/hooks.mjs b/packages/vitest-native/src/native/hooks.mjs index b3b90039e..0329dc1df 100644 --- a/packages/vitest-native/src/native/hooks.mjs +++ b/packages/vitest-native/src/native/hooks.mjs @@ -318,6 +318,12 @@ export function installRequireHooks( function presetExportsFor(request, fromFile) { const mocks = globalThis.__vitest_native_preset_mocks; if (!mocks) return NO_PRESET; + // jest.requireActual of a shadowed package: this one load is the package itself + // (jest-compat/node-registry.mjs), as Jest's requireActual gives it. + if (globalThis.__vitest_native_preset_actual === request) { + globalThis.__vitest_native_preset_actual = undefined; + return NO_PRESET; + } if (Object.prototype.hasOwnProperty.call(mocks, request)) return mocks[request]; // Subpath require of a preset package — the real deep entry would load the // package's native runtime. Exempt: JSON subpaths (package.json version diff --git a/packages/vitest-native/src/native/library-jest.mjs b/packages/vitest-native/src/native/library-jest.mjs new file mode 100644 index 000000000..5719f74f8 --- /dev/null +++ b/packages/vitest-native/src/native/library-jest.mjs @@ -0,0 +1,291 @@ +// Jest, as a library's own test support sees it. +// +// React Native libraries ship their test support for Jest: setup files that call +// `jest.mock` for their native modules (react-native-gesture-handler/jestSetup.js, +// @shopify/flash-list/jestSetup.js) and mocks that call `jest.fn` or import +// `@jest/globals` (react-native-safe-area-context/jest/mock). Under Vitest a global +// `jest` is Vitest's `vi`, whose `mock` never reaches Node's `require`, and a library +// file is not compiled by jestMockTransform, so such a setup file ran and changed +// nothing. Here a library's support files get a `jest` of their own, with Jest's +// semantics where they differ: +// +// - `jest.mock(spec, factory)` registers the factory in the per-file Node registry +// (jest-compat/node-registry.mjs), keyed from the file that called it, so every +// require of the module gets it, as under Jest's single registry; +// - `jest.requireActual` gives the module itself, past a preset's shadow; +// - `jest.fn`: an implementation a library installs while it builds its mocks +// (`jest.fn().mockImplementation(...)`, `mockReturnValue(...)`) is the mock's own, so +// `vi.resetAllMocks()` and `mockReset: true` return the mock to it, where Vitest would +// drop it (the bug class mock-reset-fragile presets had, #278/#287); +// - `@jest/globals` required from such a file is the same `jest`. +// +// The `jest` reaches a file as a function parameter around its compiled code, never as +// `globalThis.jest`: code elsewhere (RNTL's fake-timer detection) reads `typeof jest` to +// decide whether it runs under Jest. +// +// A package's test support is active once one of its support entries loads: a request +// whose leaf is `jestSetup` or `mock`, or a file under its `jest/` directory, whether a +// preset loads it or a suite migrated from Jest imports it. Its files that mention +// `jest` then get one. +// +// What a support entry registers lasts as long as the entry's module does. Each test +// file gets a fresh module registry by default, and under the hot runtime, which evicts +// node_modules per file, so the entry runs again and registers again. Under +// `isolate: false` modules outlive the file, a cached entry never runs again, and its +// registrations stay with it, as the module's other state does. +import fs from "node:fs"; +import Module from "node:module"; +import path from "node:path"; +import vm from "node:vm"; +import { createJestObject } from "../jest-compat/jest-object.mjs"; +import { nodeRegistry } from "../jest-compat/node-registry.mjs"; +import { packageNameOf, subpathLeafOf } from "./match.mjs"; + +const SUPPORT_LEAVES = new Set(["jestSetup", "mock"]); +const MENTIONS_JEST = /\bjest\b/; + +/** Packages whose test support has loaded in this worker. */ +const active = new Set(); +/** How many library-building scopes are open (support entries, their factories). */ +let building = 0; +/** The support entries being evaluated, innermost last: `{ pkg, module }`. */ +const owners = []; +/** One `jest` per file. */ +const jestByFile = new Map(); +/** Each directory's package, by its nearest named package.json (workspace links too). */ +const packageByFile = new Map(); +const projectRoot = path.resolve(process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd()); + +/** + * The package `request` loads test support of, or null: a request whose last segment + * is `jestSetup` or `mock`, or one into the package's `jest/` directory. + */ +export function supportPackageOf(request) { + if (typeof request !== "string" || request.startsWith(".") || path.isAbsolute(request)) { + return null; + } + const pkg = packageNameOf(request); + if (pkg === request) return null; + const subpath = request.slice(pkg.length + 1); + const leaf = subpathLeafOf(request); + return (leaf !== null && SUPPORT_LEAVES.has(leaf)) || subpath.split("/")[0] === "jest" + ? pkg + : null; +} + +/** Run `load` as the evaluation of `pkg`'s test support. */ +export function withinSupport(pkg, load) { + active.add(pkg); + building++; + try { + return load(); + } finally { + building--; + } +} + +/** + * The package `file` belongs to and its directory: the nearest package.json that names + * a package (a `lib/commonjs/package.json` holding only `"type"` does not). By manifest + * rather than by node_modules path, so a workspace or `file:` link, whose directory need + * not carry the package's name, is found too. Cached per directory. + */ +function packageRootOf(file) { + if (typeof file !== "string") return null; + const start = path.dirname(file); + if (packageByFile.has(start)) return packageByFile.get(start); + let root = null; + for (let dir = start; ; dir = path.dirname(dir)) { + const manifest = path.join(dir, "package.json"); + if (fs.existsSync(manifest)) { + let name; + try { + name = JSON.parse(fs.readFileSync(manifest, "utf8")).name; + } catch { + name = undefined; + } + if (typeof name === "string") { + root = { name, dir }; + break; + } + } + if (path.dirname(dir) === dir) break; + } + packageByFile.set(start, root); + return root; +} + +/** Whether `file` belongs to a package whose test support has loaded. */ +export function isSupportFile(file) { + const root = packageRootOf(file); + return root !== null && active.has(root.name); +} + +/** + * The package `file` is a test-support entry of (its `jestSetup`, `mock`, or a file + * under its `jest/`), or null: a support file loaded by `import` or a `setupFiles` entry + * reaches the CommonJS loader without the request `Module._load` sees. + */ +function supportPackageOfFile(file) { + const root = packageRootOf(file); + if (root === null) return null; + // The project's own `jest/setup.js` or `src/api/mock.ts` is not a library's support: + // giving it a library's `jest` would make its mocks outlive a reset. + if (root.dir === projectRoot || projectRoot.startsWith(root.dir + path.sep)) return null; + const rest = path.relative(root.dir, file).split(path.sep).join("/"); + const leaf = path.posix.basename(rest).replace(/\.[cm]?[jt]sx?$/, ""); + return SUPPORT_LEAVES.has(leaf) || rest.split("/")[0] === "jest" ? root.name : null; +} + +/** Whether the support entry `owner` is still the module a `require` of it returns. */ +function loaded(owner) { + return owner !== null && Module._cache[owner.module.filename] === owner.module; +} + +/** + * Start a test file: of what libraries registered, only what a still-loaded support + * entry made is kept (see the top of this file), and only those packages stay active. + */ +export function beginTestFile() { + active.clear(); + jestByFile.clear(); + globalThis.__vitest_native_jest_registry?.clear({ + keep(entry) { + if (!entry.library || !loaded(entry.owner)) return false; + active.add(entry.owner.pkg); + return true; + }, + }); +} + +const BASELINE_SETTERS = [ + ["mockImplementation", (impl) => impl], + ["mockReturnValue", (value) => () => value], + ["mockResolvedValue", (value) => () => Promise.resolve(value)], + ["mockRejectedValue", (value) => () => Promise.reject(value)], +]; + +/** The `jest` a library file sees. */ +export function libraryJestFor(vi, file) { + let jest = jestByFile.get(file); + if (jest) return jest; + const registry = () => nodeRegistry(); + const base = createJestObject(vi); + // `jest.fn` whose built implementation is the mock's own: a delegate Vitest keeps + // through a reset, which calls whatever implementation the library installed. + const fn = (impl) => { + let own = impl; + const mock = base.fn(function (...args) { + return own === undefined ? undefined : own.apply(this, args); + }); + for (const [name, toImpl] of BASELINE_SETTERS) { + const set = mock[name]; + mock[name] = (value) => { + if (building === 0) return set.call(mock, value); + own = toImpl(value); + return mock; + }; + } + return mock; + }; + // A factory the library registers runs later, when the module is first required; + // what it builds is part of the library's mocks too, and belongs to the same entry. + const asBuilding = (factory, owner) => () => { + building++; + if (owner !== null) owners.push(owner); + try { + return factory(); + } finally { + if (owner !== null) owners.pop(); + building--; + } + }; + const mock = (spec, factory) => { + const owner = owners.at(-1) ?? null; + registry().register(file, spec, asBuilding(factory ?? (() => ({})), owner), { + library: true, + owner, + }); + return jest; + }; + jest = createJestObject(vi, { + fn, + mock, + doMock: mock, + unmock: (spec) => { + registry().unregister(file, spec); + return jest; + }, + requireActual: (spec) => registry().require(spec, file, true), + requireMock: (spec) => registry().require(spec, file, false), + }); + jestByFile.set(file, jest); + return jest; +} + +/** + * Install the pieces in the worker: a support file's compiled code runs with its own + * `jest`, and its `@jest/globals` is that `jest`. Once per worker. + */ +export function installLibraryJest(vi) { + if (globalThis.__vitest_native_library_jest) return; + Object.defineProperty(globalThis, "__vitest_native_library_jest", { + configurable: true, + value: (file) => libraryJestFor(vi, file), + }); + const compile = Module.prototype._compile; + Module.prototype._compile = function (content, filename, ...rest) { + const entryOf = supportPackageOfFile(filename); + if (entryOf !== null) active.add(entryOf); + if ( + typeof content === "string" && + isSupportFile(filename) && + MENTIONS_JEST.test(content) && + rest[0] !== "module" + ) { + // On the first line, so line numbers stay. A parameter rather than a `var`, and + // the code in a function of its own, so a file that declares its own `jest` + // (`const { jest } = require("@jest/globals")`) still compiles and shadows it. + const wrapped = + `(function (jest) {return (function () {${stripShebang(content)}\n}).call(this);}).call(this, ` + + `globalThis.__vitest_native_library_jest(__filename));`; + // An ES module's syntax cannot sit in a function body: such a file is left as it + // is, for Node to load as a module. + if (parses(wrapped, filename)) content = wrapped; + } + // A support entry reached by `import` or `setupFiles` builds the library's mocks + // as one reached by `require` does (withinSupport), and owns what it registers. + if (entryOf === null) return compile.call(this, content, filename, ...rest); + building++; + owners.push({ pkg: entryOf, module: this }); + try { + return compile.call(this, content, filename, ...rest); + } finally { + owners.pop(); + building--; + } + }; + const load = Module._load; + Module._load = function (request, parent, ...rest) { + if (request === "@jest/globals" && isSupportFile(parent?.filename)) { + const jest = libraryJestFor(vi, parent.filename); + return { jest, expect: globalThis.expect, __esModule: true, default: { jest } }; + } + const pkg = supportPackageOf(request); + if (pkg !== null) return withinSupport(pkg, () => load.call(this, request, parent, ...rest)); + return load.call(this, request, parent, ...rest); + }; +} + +/** Whether `code` parses as a script; it is not run. */ +function parses(code, filename) { + try { + return new vm.Script(code, { filename }) instanceof vm.Script; + } catch { + return false; + } +} + +function stripShebang(code) { + return code.startsWith("#!") ? code.replace(/^#!.*/, "") : code; +} diff --git a/packages/vitest-native/src/native/setup.mjs b/packages/vitest-native/src/native/setup.mjs index 501224ef4..7979533a6 100644 --- a/packages/vitest-native/src/native/setup.mjs +++ b/packages/vitest-native/src/native/setup.mjs @@ -16,6 +16,7 @@ import { VitestNativeError } from "../errors.mjs"; import { importPresetModule, presetModulePaths } from "../preset-modules.mjs"; import { installNitroProxy } from "./nitro.mjs"; import { createExpoNativeModuleResolver } from "./expo-native-modules.mjs"; +import { beginTestFile, installLibraryJest } from "./library-jest.mjs"; import { cacheRootFor } from "./transform.mjs"; import { installKnownNativeModules } from "./native-modules.mjs"; @@ -289,6 +290,12 @@ installRequireHooks( ); // After the hooks: the polyfill is Flow-typed and compiled by them (see globals.mjs). installErrorUtils(projectRoot); +// Libraries' own test support (their jestSetup and mock files) runs with a `jest` of +// its own, with Jest's module-registry semantics (library-jest.mjs). +installLibraryJest(vi); +// Each test file keeps only what a still-loaded library support module registered, +// under every pool: the hot runtime and `isolate: false` reuse a worker. +beginTestFile(); // Through Vitest, so a TypeScript preset module loads. Its export lists already // reached the ESM loader from the plugin; a module the plugin did not read would be // served by the real package there. diff --git a/packages/vitest-native/tests-native/fixtures/project-own-support/src/api/mock.cjs b/packages/vitest-native/tests-native/fixtures/project-own-support/src/api/mock.cjs new file mode 100644 index 000000000..5a8170156 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/project-own-support/src/api/mock.cjs @@ -0,0 +1,2 @@ +// The project's own src/api/mock (no package.json of its own: it is the project's). +module.exports = { isLibraryJest: typeof jest !== "undefined" && jest !== globalThis.jest }; diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/NativeThing.js b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/NativeThing.js new file mode 100644 index 000000000..71addcea2 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/NativeThing.js @@ -0,0 +1,8 @@ +module.exports = { + read() { + throw new Error("NativeThing is a native module"); + }, + count() { + throw new Error("NativeThing is a native module"); + }, +}; diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/index.js b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/index.js new file mode 100644 index 000000000..cc441b8dc --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/index.js @@ -0,0 +1,5 @@ +// A library shaped like the React Native ones that ship Jest support: its JS calls into +// a native module that only exists on a device. +const NativeThing = require("./NativeThing"); +exports.read = () => NativeThing.read(); +exports.count = () => NativeThing.count(); diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/commented.js b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/commented.js new file mode 100644 index 000000000..c48761407 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/commented.js @@ -0,0 +1,4 @@ +/* +export of the library's helpers, for tests; import them from here. +*/ +module.exports = { isLibraryJest: typeof jest !== "undefined" && jest !== globalThis.jest }; diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/esm-min.js b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/esm-min.js new file mode 100644 index 000000000..37ed99e1f --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/esm-min.js @@ -0,0 +1,3 @@ +// A minified ES module that mentions jest. +// oxfmt-ignore +const viaEsm="min";export{viaEsm}; diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/esm.js b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/esm.js new file mode 100644 index 000000000..68b58319f --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/esm.js @@ -0,0 +1,2 @@ +// A test helper published as an ES module, which mentions jest in a comment only. +export const viaEsm = "esm"; diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/mock.js b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/mock.js new file mode 100644 index 000000000..dc519c12e --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jest/mock.js @@ -0,0 +1,5 @@ +// As react-native-safe-area-context/jest/mock does: the real package, with a member +// replaced, through @jest/globals. +const { jest } = require("@jest/globals"); +const actual = jest.requireActual("vn-lib-jest-support"); +module.exports = { ...actual, extra: jest.fn(() => "extra"), actualRead: actual.read }; diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jestSetup.js b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jestSetup.js new file mode 100644 index 000000000..e5e062c9b --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/jestSetup.js @@ -0,0 +1,5 @@ +// As react-native-gesture-handler/jestSetup.js does: replace the native module. +jest.mock("./NativeThing", () => ({ + read: jest.fn().mockReturnValue("mocked"), + count: jest.fn().mockImplementation(() => 3), +})); diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/package.json b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/package.json new file mode 100644 index 000000000..8d4c23ea3 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-jest-support/package.json @@ -0,0 +1,6 @@ +{ + "name": "vn-lib-jest-support", + "version": "1.0.0", + "private": true, + "main": "index.js" +} diff --git a/packages/vitest-native/tests-native/fixtures/vn-ws-lib/index.js b/packages/vitest-native/tests-native/fixtures/vn-ws-lib/index.js new file mode 100644 index 000000000..ea1babafc --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-ws-lib/index.js @@ -0,0 +1,3 @@ +// A workspace library, linked from outside node_modules, whose directory is not named +// after the package. +exports.read = () => require("./native").read(); diff --git a/packages/vitest-native/tests-native/fixtures/vn-ws-lib/jestSetup.js b/packages/vitest-native/tests-native/fixtures/vn-ws-lib/jestSetup.js new file mode 100644 index 000000000..57de4aba5 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-ws-lib/jestSetup.js @@ -0,0 +1 @@ +jest.mock("./native", () => ({ read: () => "mocked" })); diff --git a/packages/vitest-native/tests-native/fixtures/vn-ws-lib/native.js b/packages/vitest-native/tests-native/fixtures/vn-ws-lib/native.js new file mode 100644 index 000000000..b54546546 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-ws-lib/native.js @@ -0,0 +1,3 @@ +exports.read = () => { + throw new Error("native module"); +}; diff --git a/packages/vitest-native/tests-native/fixtures/vn-ws-lib/package.json b/packages/vitest-native/tests-native/fixtures/vn-ws-lib/package.json new file mode 100644 index 000000000..1ae25777f --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-ws-lib/package.json @@ -0,0 +1,6 @@ +{ + "name": "@vn-ws/lib-with-setup", + "version": "1.0.0", + "private": true, + "main": "index.js" +} diff --git a/packages/vitest-native/tests-native/jest-registry-no-isolate/c1-library-setup.test.ts b/packages/vitest-native/tests-native/jest-registry-no-isolate/c1-library-setup.test.ts new file mode 100644 index 000000000..0038224c6 --- /dev/null +++ b/packages/vitest-native/tests-native/jest-registry-no-isolate/c1-library-setup.test.ts @@ -0,0 +1,8 @@ +import { createRequire } from "node:module"; +import { expect, test } from "vitest"; + +test("a library's jestSetup imported by a setup file mocks its native module (file 1)", () => { + expect(createRequire(import.meta.url)("vn-lib-jest-support/NativeThing.js").read()).toBe( + "mocked", + ); +}); diff --git a/packages/vitest-native/tests-native/jest-registry-no-isolate/c2-library-setup.test.ts b/packages/vitest-native/tests-native/jest-registry-no-isolate/c2-library-setup.test.ts new file mode 100644 index 000000000..d3fbeb3be --- /dev/null +++ b/packages/vitest-native/tests-native/jest-registry-no-isolate/c2-library-setup.test.ts @@ -0,0 +1,8 @@ +import { createRequire } from "node:module"; +import { expect, test } from "vitest"; + +test("a library's jestSetup imported by a setup file mocks its native module (file 2)", () => { + expect(createRequire(import.meta.url)("vn-lib-jest-support/NativeThing.js").read()).toBe( + "mocked", + ); +}); diff --git a/packages/vitest-native/tests-native/jest-registry-no-isolate/library-setup.ts b/packages/vitest-native/tests-native/jest-registry-no-isolate/library-setup.ts new file mode 100644 index 000000000..6f1058671 --- /dev/null +++ b/packages/vitest-native/tests-native/jest-registry-no-isolate/library-setup.ts @@ -0,0 +1,3 @@ +// A migrated suite's own setup file importing a library's jestSetup, which runs once +// per worker under `isolate: false`: its mocks have to reach every file (c1, c2). +import "vn-lib-jest-support/jestSetup.js"; diff --git a/packages/vitest-native/tests-native/jest-registry-require-actual.test.ts b/packages/vitest-native/tests-native/jest-registry-require-actual.test.ts index 3f1b896b8..50f9ddee0 100644 --- a/packages/vitest-native/tests-native/jest-registry-require-actual.test.ts +++ b/packages/vitest-native/tests-native/jest-registry-require-actual.test.ts @@ -57,3 +57,18 @@ describe("require() from a test file", () => { expect(require("./fixtures/alias-app/registry/storage")).toBe(required); }); }); + +describe("jest.requireActual of a package a preset shadows", () => { + it("is the package, not the preset", () => { + // The safe-area-context preset shadows the package by name; Jest's requireActual + // gives the real one, which a library's own mock spreads (its jest/mock does). + const actual = jest.requireActual>("react-native-safe-area-context"); + const shadowed = jest.requireMock>("react-native-safe-area-context"); + expect(typeof actual.SafeAreaListener).toBe("function"); + expect(shadowed.SafeAreaListener).toBeUndefined(); + // Only that load: the next one by name is the preset again. + expect(jest.requireMock>("react-native-safe-area-context")).toBe( + shadowed, + ); + }); +}); diff --git a/packages/vitest-native/tests-native/library-jest-import.test.ts b/packages/vitest-native/tests-native/library-jest-import.test.ts new file mode 100644 index 000000000..ed6e26295 --- /dev/null +++ b/packages/vitest-native/tests-native/library-jest-import.test.ts @@ -0,0 +1,13 @@ +/** + * A library's setup reached by `import` (a migrated suite's setup file, a `setupFiles` + * entry) gets the same Jest semantics as one reached by `require`: the CommonJS loader + * compiles the file without the request `Module._load` sees, so the package is activated + * from the file itself (native/library-jest.mjs). + */ +import "vn-lib-jest-support/jestSetup.js"; +import { createRequire } from "node:module"; +import { expect, it } from "vitest"; + +it("mocks the library's native module for its own require of it", () => { + expect(createRequire(import.meta.url)("vn-lib-jest-support").read()).toBe("mocked"); +}); diff --git a/packages/vitest-native/tests-native/library-jest.test.ts b/packages/vitest-native/tests-native/library-jest.test.ts new file mode 100644 index 000000000..ab0e6fe73 --- /dev/null +++ b/packages/vitest-native/tests-native/library-jest.test.ts @@ -0,0 +1,91 @@ +/** + * A library's own Jest support runs with Jest's semantics (native/library-jest.mjs): + * its setup file's `jest.mock` reaches every require of the module, its mock's + * `@jest/globals` and `jest.requireActual` work, and an implementation it installs while + * building its mocks survives a reset. The fixture (fixtures/vn-lib-jest-support) is + * shaped like react-native-gesture-handler's jestSetup.js and safe-area-context's + * jest/mock. + */ +import { createRequire } from "node:module"; +import path from "node:path"; +import { describe, expect, it, vi } from "vitest"; +// @ts-expect-error — runtime .mjs +import { beginTestFile } from "../dist/native/library-jest.mjs"; + +const require = createRequire(import.meta.url); +const globalJestBefore = (globalThis as { jest?: unknown }).jest; + +// As a suite migrated from Jest lists `react-native-gesture-handler/jestSetup`. +require("vn-lib-jest-support/jestSetup"); + +describe("a library's jestSetup", () => { + it("mocks the library's native module for its own require of it", () => { + const lib = require("vn-lib-jest-support"); + expect(lib.read()).toBe("mocked"); + expect(lib.count()).toBe(3); + }); + + it("keeps the implementations it installed through vi.resetAllMocks()", () => { + const lib = require("vn-lib-jest-support"); + vi.resetAllMocks(); + // Vitest's reset drops `mockReturnValue`/`mockImplementation`; these were the + // library's own, so the mocks return to them. + expect(lib.read()).toBe("mocked"); + expect(lib.count()).toBe(3); + }); +}); + +describe("a library's mock", () => { + it("gets @jest/globals and the real package from jest.requireActual", () => { + const mock = require("vn-lib-jest-support/jest/mock"); + expect(mock.extra()).toBe("extra"); + // The actual package, over the native module the setup file mocked. + expect(mock.actualRead()).toBe("mocked"); + }); +}); + +it("leaves the global jest as it was", () => { + // RNTL and others read `typeof jest` to decide whether they run under Jest, so the + // library's `jest` is its files' own, never the global one. + expect((globalThis as { jest?: unknown }).jest).toBe(globalJestBefore); +}); + +it("loads a support file published as an ES module that mentions jest", () => { + // Its syntax cannot sit in a function body, so it is not given a `jest`. + expect(require("vn-lib-jest-support/jest/esm.js").viaEsm).toBe("esm"); + expect(require("vn-lib-jest-support/jest/esm-min.js").viaEsm).toBe("min"); +}); + +it("gives a CommonJS support file its jest when a comment line starts with `export`", () => { + expect(require("vn-lib-jest-support/jest/commented.js").isLibraryJest).toBe(true); +}); + +it("gives no library jest to the project's own mock files", () => { + // Its mocks would otherwise keep their implementations through a reset. + const file = path.join(import.meta.dirname, "fixtures/project-own-support/src/api/mock.cjs"); + expect(require(file).isLibraryJest).toBe(false); +}); + +it("serves a workspace library's own jestSetup, linked from outside node_modules", () => { + const dir = path.join(import.meta.dirname, "fixtures", "vn-ws-lib"); + require(path.join(dir, "jestSetup.js")); + expect(require(path.join(dir, "index.js")).read()).toBe("mocked"); +}); + +describe("at the next test file in the same worker", () => { + // The native setup calls beginTestFile as each file starts. A reused worker + // (`isolate: false`) keeps modules, so a support module that will not run again + // keeps its mocks; one gone from the module cache runs again and registers again. + const nativeThing = () => require("vn-lib-jest-support/NativeThing.js"); + + it("keeps what a still-loaded support module registered", () => { + beginTestFile(); + expect(nativeThing().read()).toBe("mocked"); + }); + + it("drops what a support module no longer loaded registered", () => { + delete require.cache[require.resolve("vn-lib-jest-support/jestSetup")]; + beginTestFile(); + expect(() => nativeThing().read()).toThrow("NativeThing is a native module"); + }); +}); diff --git a/packages/vitest-native/tests-native/vitest.jest-registry-no-isolate.config.mts b/packages/vitest-native/tests-native/vitest.jest-registry-no-isolate.config.mts index d6576d838..65b17d20b 100644 --- a/packages/vitest-native/tests-native/vitest.jest-registry-no-isolate.config.mts +++ b/packages/vitest-native/tests-native/vitest.jest-registry-no-isolate.config.mts @@ -1,7 +1,8 @@ // jest-compat's per-file mock registry in a reused worker WITHOUT the hot runtime: // `isolate: false`, one worker, files in name order (b1 mocks, b2 and b3 must not see // it). The hot runtime clears the registry through its state manifest; this run has -// no hot runtime, so it proves the registry clears itself when the file changes. +// no hot runtime, so it proves the registry clears itself when the file changes. A +// library's mocks, from a setup file that runs once (c1, c2), stay with its module. import path from "node:path"; import { fileURLToPath } from "node:url"; import { defineConfig } from "vitest/config"; @@ -25,7 +26,10 @@ export default defineConfig({ environment: "node", globals: true, isolate: false, - setupFiles: [path.resolve(here, "../dist/jest-compat/setup.mjs")], + setupFiles: [ + path.resolve(here, "../dist/jest-compat/setup.mjs"), + path.resolve(here, "jest-registry-no-isolate/library-setup.ts"), + ], include: ["tests-native/jest-registry-no-isolate/*.test.ts"], fileParallelism: false, maxWorkers: 1, From 0cbcf216a907cd134dc7b7149c91d3396a4d3402 Mon Sep 17 00:00:00 2001 From: Daniel Fry <95628792+danfry1@users.noreply.github.com> Date: Wed, 28 Oct 2026 22:40:54 +0000 Subject: [PATCH 2/4] fix(native): a package with a react-native field is one module, imported or required An import resolved such a package through its react-native field and a require through main, so a library required by another got a second copy, and a context one copy created was not the other's. A bare require now resolves the react-native field, as Metro and Vite's import do. --- .changeset/library-test-support.md | 2 + bun.lock | 3 ++ packages/vitest-native/package.json | 1 + .../src/jest-compat/node-registry.mjs | 20 +++++++- packages/vitest-native/src/native/hooks.mjs | 19 ++++++++ packages/vitest-native/src/native/resolve.mjs | 47 +++++++++++++++++++ .../fixtures/vn-lib-two-entries/consumer.js | 2 + .../fixtures/vn-lib-two-entries/lib/index.js | 3 ++ .../fixtures/vn-lib-two-entries/package.json | 7 +++ .../fixtures/vn-lib-two-entries/src/index.js | 3 ++ .../jest-mock-library-own-mock.test.tsx | 25 ++++++++++ .../one-instance-per-package.test.ts | 30 ++++++++++++ 12 files changed, 161 insertions(+), 1 deletion(-) create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/consumer.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/lib/index.js create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/package.json create mode 100644 packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/src/index.js create mode 100644 packages/vitest-native/tests-native/jest-mock-library-own-mock.test.tsx create mode 100644 packages/vitest-native/tests-native/one-instance-per-package.test.ts diff --git a/.changeset/library-test-support.md b/.changeset/library-test-support.md index a97eddbbb..092bd5739 100644 --- a/.changeset/library-test-support.md +++ b/.changeset/library-test-support.md @@ -5,3 +5,5 @@ 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. + +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. diff --git a/bun.lock b/bun.lock index cd36e35e3..baad94967 100644 --- a/bun.lock +++ b/bun.lock @@ -93,6 +93,7 @@ "vite": "^8.3.4", "vitest": "5.0.5", "vn-lib-jest-support": "file:./tests-native/fixtures/vn-lib-jest-support", + "vn-lib-two-entries": "file:./tests-native/fixtures/vn-lib-two-entries", }, "peerDependencies": { "@babel/core": "*", @@ -1985,6 +1986,8 @@ "vitest-native/vn-lib-jest-support": ["vn-lib-jest-support@file:packages/vitest-native/tests-native/fixtures/vn-lib-jest-support", {}], + "vitest-native/vn-lib-two-entries": ["vn-lib-two-entries@file:packages/vitest-native/tests-native/fixtures/vn-lib-two-entries", {}], + "wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], "xml2js/xmlbuilder": ["xmlbuilder@11.0.1", "", {}, "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA=="], diff --git a/packages/vitest-native/package.json b/packages/vitest-native/package.json index 12b97db2d..7791b532f 100644 --- a/packages/vitest-native/package.json +++ b/packages/vitest-native/package.json @@ -174,6 +174,7 @@ "rn-condition-lib": "file:./tests-native/fixtures/rn-condition-lib", "rn-ecosystem-lib": "file:./tests-native/fixtures/rn-ecosystem-lib", "vn-lib-jest-support": "file:./tests-native/fixtures/vn-lib-jest-support", + "vn-lib-two-entries": "file:./tests-native/fixtures/vn-lib-two-entries", "rn-mainfield-lib": "file:./tests-native/fixtures/rn-mainfield-lib", "rn-platform-flow-lib": "file:./tests-native/fixtures/rn-platform-flow-lib", "rn-singleton-lib": "file:./tests-native/fixtures/rn-singleton-lib", diff --git a/packages/vitest-native/src/jest-compat/node-registry.mjs b/packages/vitest-native/src/jest-compat/node-registry.mjs index 74b062c1b..f913f54f7 100644 --- a/packages/vitest-native/src/jest-compat/node-registry.mjs +++ b/packages/vitest-native/src/jest-compat/node-registry.mjs @@ -17,6 +17,7 @@ import { expandAlias } from "./aliases.mjs"; import { resolvePlatformFile, resolveRelativePlatformFile } from "../native/resolve.mjs"; import { resetEvaluatedModules, restoreEvaluatedModules } from "../native/module-reset.mjs"; import { VitestNativeError } from "../errors.mjs"; +import { owningPackageOfFile, packageNameOf } from "../native/match.mjs"; const STATE = "__vitest_native_jest_registry"; /** The manifest id under which the hot runtime clears the registry per file. */ @@ -417,6 +418,21 @@ function viteInstanceOf(filename) { return NONE; } +/** + * Whether a mock registered for a whole package (`jest.mock('react-native-reanimated', + * …)`) is being reached by the package's own relative import of its entry. The engine + * resolves a package as Metro does, through its `react-native` field, so the package's + * entry and the file its own mock imports (`./index`) are one file. Under Jest they are + * not: it resolves the package through `main` (lib/module/index.js), so the factory + * `() => require('react-native-reanimated/mock')` loads the real `src/index` unmocked. + * Serving the mock there would be the factory requiring itself. + */ +function isPackageOwnRelativeLoad(entry, request, parent) { + if (!request.startsWith(".") || typeof parent?.filename !== "string") return false; + if (typeof entry.spec !== "string" || packageNameOf(entry.spec) !== entry.spec) return false; + return owningPackageOfFile(parent.filename) === entry.spec; +} + function installLoadHook(state) { const origLoad = Module._load; Module._load = function (request, parent, ...rest) { @@ -432,7 +448,9 @@ function installLoadHook(state) { } const filename = state.resolve(request, parent); const entry = state.lookup(filename, request); - if (entry !== undefined) return state.valueOf(entry); + if (entry !== undefined && !isPackageOwnRelativeLoad(entry, request, parent)) { + return state.valueOf(entry); + } // A module Node already holds stays the one `require` returns: switching a later // require to Vite's copy would change its identity mid-file. if ( diff --git a/packages/vitest-native/src/native/hooks.mjs b/packages/vitest-native/src/native/hooks.mjs index 0329dc1df..a64d882bc 100644 --- a/packages/vitest-native/src/native/hooks.mjs +++ b/packages/vitest-native/src/native/hooks.mjs @@ -11,6 +11,7 @@ import { resolveRelativePlatformFile, resolveRelativeWithExtensions, resolveDeepPackageFile, + resolvePackageMainField, } from "./resolve.mjs"; import { NODE_MODULES_PATH, @@ -423,6 +424,24 @@ export function installRequireHooks( : resolveRelativePlatformFile(request, parent.filename, platform, activeSourceExts); if (resolved) resolved = asNodeResolves(resolved); } + // A whole package with a `react-native` field: the file Metro and Vite's import + // resolve it to, so an import and a require are one module (resolve.mjs). + if ( + !resolved && + parent?.filename && + packageNameOf(request) === request && + request !== "react-native" && + !request.startsWith("@react-native/") && + !Module.isBuiltin(request) + ) { + const entry = resolvePackageMainField( + request, + path.dirname(parent.filename), + platform, + activeSourceExts, + ); + if (entry) resolved = asNodeResolves(entry); + } if (!resolved) { try { resolved = origResolve.call(this, request, parent, ...rest); diff --git a/packages/vitest-native/src/native/resolve.mjs b/packages/vitest-native/src/native/resolve.mjs index 9869e5582..c9e96e4f1 100644 --- a/packages/vitest-native/src/native/resolve.mjs +++ b/packages/vitest-native/src/native/resolve.mjs @@ -218,6 +218,53 @@ export function resolveDeepPackageFile(request, fromDir, platform, sourceExts = return resolvePlatformFile(stem, platform, sourceExts); } +/** + * The entry a bare `request` for a whole package resolves to through its `react-native` + * field, as Metro resolves it and as Vite does for an `import` under the native engine + * (native/apply.ts `resolve.mainFields`), or null. Node's `require` reads `main`, so a + * package naming a different file in each was loaded twice, from two files: the test's + * import got one instance and a library's require another (react-native-worklets: + * `src/index.ts` and `lib/module/index.js`). Only for a + * package without an `exports` map, which Node and Vite already read alike through the + * `react-native` condition. + */ +export function resolvePackageMainField( + request, + fromDir, + platform, + sourceExts = METRO_SOURCE_EXTS, +) { + // Every bare require reaches here, so both lookups are cached: which directory holds + // the package from `fromDir`, and what that package.json says. Neither changes within + // a worker's life. + const dirKey = `${fromDir}\0${request}`; + let pkgDir = packageDirCache.get(dirKey); + if (pkgDir === undefined) { + pkgDir = findPackageDir(fromDir, request); + packageDirCache.set(dirKey, pkgDir); + } + if (!pkgDir) return null; + let manifest = manifestCache.get(pkgDir); + if (manifest === undefined) { + try { + manifest = JSON.parse(fs.readFileSync(path.join(pkgDir, "package.json"), "utf8")); + } catch { + manifest = null; + } + manifestCache.set(pkgDir, manifest); + } + if (!manifest) return null; + if (manifest.exports !== undefined || typeof manifest["react-native"] !== "string") return null; + const target = path.join(pkgDir, manifest["react-native"]); + try { + if (fs.statSync(target).isFile()) return target; + } catch {} + return resolvePlatformFile(target.replace(/\.[cm]?[jt]sx?$/, ""), platform, sourceExts); +} + +const packageDirCache = new Map(); +const manifestCache = new Map(); + function findPackageDir(startDir, pkg) { let dir = path.resolve(startDir); for (;;) { diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/consumer.js b/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/consumer.js new file mode 100644 index 000000000..a357278e0 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/consumer.js @@ -0,0 +1,2 @@ +// A library requiring the package by name, as a Node-owned library does. +module.exports = () => require("vn-lib-two-entries"); diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/lib/index.js b/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/lib/index.js new file mode 100644 index 000000000..72a56a5ae --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/lib/index.js @@ -0,0 +1,3 @@ +// The `main` build, which Node's require read. +exports.build = "main"; +exports.store = { value: 0 }; diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/package.json b/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/package.json new file mode 100644 index 000000000..0b1a8ddf4 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/package.json @@ -0,0 +1,7 @@ +{ + "name": "vn-lib-two-entries", + "version": "1.0.0", + "private": true, + "main": "lib/index.js", + "react-native": "src/index.js" +} diff --git a/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/src/index.js b/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/src/index.js new file mode 100644 index 000000000..d5c0a8989 --- /dev/null +++ b/packages/vitest-native/tests-native/fixtures/vn-lib-two-entries/src/index.js @@ -0,0 +1,3 @@ +// The React Native build, as Metro and an import resolve it. +exports.build = "react-native"; +exports.store = { value: 0 }; diff --git a/packages/vitest-native/tests-native/jest-mock-library-own-mock.test.tsx b/packages/vitest-native/tests-native/jest-mock-library-own-mock.test.tsx new file mode 100644 index 000000000..4e7d6f3c7 --- /dev/null +++ b/packages/vitest-native/tests-native/jest-mock-library-own-mock.test.tsx @@ -0,0 +1,25 @@ +/** + * The line a Jest suite using Reanimated carries: + * `jest.mock('react-native-reanimated', () => require('react-native-reanimated/mock'))`. + * Reanimated's mock loads the real package with `import … from './index'`. The engine + * resolves the package as Metro does (its `react-native` field, `src/index`), so that + * file is the one the mock is registered for; under Jest it is not (Jest resolves + * `main`), and the package's own relative import gets the real module. It does here too + * (jest-compat/node-registry.mjs, isPackageOwnRelativeLoad), where it was reported as the + * factory requiring itself. + */ +import { describe, expect, it } from "vitest"; +import { withTiming, interpolateColor } from "react-native-reanimated"; + +declare const jest: { mock(path: string, factory: () => unknown): void }; + +jest.mock("react-native-reanimated", () => require("react-native-reanimated/mock")); + +describe("jest.mock of a package with its own mock", () => { + it("loads, and is the mock", () => { + expect(typeof interpolateColor).toBe("function"); + const finished: unknown[] = []; + withTiming(1, {}, (done?: boolean) => finished.push(done)); + expect(finished).toEqual([true]); + }); +}); diff --git a/packages/vitest-native/tests-native/one-instance-per-package.test.ts b/packages/vitest-native/tests-native/one-instance-per-package.test.ts new file mode 100644 index 000000000..7a135ca52 --- /dev/null +++ b/packages/vitest-native/tests-native/one-instance-per-package.test.ts @@ -0,0 +1,30 @@ +/** + * A package Node owns is one module, however it is reached. Its `react-native` field and + * its `main` can name different files; an `import` resolves the first (Vite's main + * fields, as Metro) and a `require` read the second, so a test and a library requiring + * the package held separate instances, and state one wrote the other never saw + * (react-native-worklets: `src/index.ts` and `lib/module/index.js`). A bare require now + * resolves the `react-native` field too (native/resolve.mjs, resolvePackageMainField). + */ +import { createRequire } from "node:module"; +import * as imported from "vn-lib-two-entries"; +import * as worklets from "react-native-worklets"; +import { expect, it } from "vitest"; + +const require = createRequire(import.meta.url); + +it("gives an import and a require of a package the same instance, its React Native build", () => { + const required = require("vn-lib-two-entries"); + expect(imported.build).toBe("react-native"); + expect(required.build).toBe("react-native"); + expect(required.store).toBe(imported.store); +}); + +it("gives a library's require of it that instance too", () => { + const fromLibrary = require("vn-lib-two-entries/consumer.js")(); + expect(fromLibrary.store).toBe(imported.store); +}); + +it("holds for react-native-worklets, which runs as itself", () => { + expect(require("react-native-worklets").runOnUI).toBe(worklets.runOnUI); +}); From 4d411824a86fd0106d5acd8f42ed78ab1451e8d8 Mon Sep 17 00:00:00 2001 From: Daniel Fry <95628792+danfry1@users.noreply.github.com> Date: Wed, 28 Oct 2026 22:42:00 +0000 Subject: [PATCH 3/4] feat(presets): worklets, safe-area-context, keyboard-controller, bottom-sheet and netinfo are their library's own mock under the native engine The hand-written presets drifted from what each library ships for Jest: missing names, different resting values, and hooks that were not mock functions. Under the native engine each is now the library's own mock module, as a Jest suite installs it with jest.mock; the mock engine keeps the hand-written presets. --- .changeset/library-test-support.md | 6 ++ .changeset/reanimated-own-mock.md | 4 +- README.md | 10 +- packages/vitest-native/README.md | 10 +- .../vitest-native/src/cli/babel-config.ts | 19 +--- packages/vitest-native/src/cli/doctor.ts | 2 +- packages/vitest-native/src/cli/manifest.ts | 3 +- packages/vitest-native/src/helpers.ts | 15 +++ packages/vitest-native/src/native/match.mjs | 6 +- packages/vitest-native/src/plugin.ts | 11 ++- packages/vitest-native/src/preset-map.ts | 18 +--- .../vitest-native/src/presets/bottom-sheet.ts | 15 ++- .../src/presets/keyboard-controller.ts | 15 ++- .../vitest-native/src/presets/library-mock.ts | 97 +++++++++++++++++++ packages/vitest-native/src/presets/netinfo.ts | 14 ++- .../vitest-native/src/presets/reanimated.ts | 75 +++----------- .../vitest-native/src/presets/safe-area.ts | 18 +++- .../vitest-native/src/presets/worklets.ts | 34 ++++--- .../jest-registry-require-actual.test.ts | 12 ++- .../tests-native/third-party-presets.test.tsx | 4 +- .../tests-native/third-party-stack.test.tsx | 24 +++-- .../tests/migrate-discovery.test.ts | 21 ---- .../vitest-native/tests/preset-engine.test.ts | 29 ++---- .../tests/preset-library-mocks.test.ts | 26 +++++ .../tests/preset-mock-reset.test.ts | 12 +++ website/guide/helpers.md | 2 +- website/guide/presets.md | 10 +- 27 files changed, 316 insertions(+), 196 deletions(-) create mode 100644 packages/vitest-native/src/presets/library-mock.ts diff --git a/.changeset/library-test-support.md b/.changeset/library-test-support.md index 092bd5739..5faebe565 100644 --- a/.changeset/library-test-support.md +++ b/.changeset/library-test-support.md @@ -6,4 +6,10 @@ Under the native engine, React Native libraries' own Jest support runs with 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 `` 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`; `` 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. + 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. diff --git a/.changeset/reanimated-own-mock.md b/.changeset/reanimated-own-mock.md index 61cede968..227857a25 100644 --- a/.changeset/reanimated-own-mock.md +++ b/.changeset/reanimated-own-mock.md @@ -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. diff --git a/README.md b/README.md index ba28aa36a..41a4e834e 100644 --- a/README.md +++ b/README.md @@ -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.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` | `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.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 `` 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.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 | diff --git a/packages/vitest-native/README.md b/packages/vitest-native/README.md index f5afe836c..83c97b399 100644 --- a/packages/vitest-native/README.md +++ b/packages/vitest-native/README.md @@ -541,22 +541,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.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` | `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.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 `` 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.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 | diff --git a/packages/vitest-native/src/cli/babel-config.ts b/packages/vitest-native/src/cli/babel-config.ts index a77a2ca61..a0debe9f4 100644 --- a/packages/vitest-native/src/cli/babel-config.ts +++ b/packages/vitest-native/src/cli/babel-config.ts @@ -10,12 +10,7 @@ import { createRequire } from "node:module"; import fs from "node:fs"; import path from "node:path"; -import { - AUTO_DETECT_PRESETS, - autoDetectedPresetApplies, - presetShadowing, - type PresetName, -} from "../preset-map.js"; +import { AUTO_DETECT_PRESETS, presetShadowing, type PresetName } from "../preset-map.js"; import { installedManifest, installedMajor } from "./manifest.js"; // https://babeljs.io/docs/config-files: one project-wide config, plus one @@ -208,18 +203,6 @@ function workletReason(pkg: string, active: readonly PresetName[], root: string) } if (!installedManifest(root, pkg)) return `transforms worklets for ${pkg}, which is not installed.`; - // Under the native engine worklets runs as itself, in its JS implementation, which - // calls a worklet as the plain function it is (NATIVE_ENGINE_RUNS_PACKAGES). - if ( - preset && - !active.includes(preset) && - !autoDetectedPresetApplies(preset, "native", undefined, root) - ) { - return ( - `transforms worklets for ${pkg}, which runs as itself under the native engine, in its ` + - `JS implementation, where a worklet is called as a plain function.` - ); - } return null; } diff --git a/packages/vitest-native/src/cli/doctor.ts b/packages/vitest-native/src/cli/doctor.ts index fa1f0f06b..457878dc5 100644 --- a/packages/vitest-native/src/cli/doctor.ts +++ b/packages/vitest-native/src/cli/doctor.ts @@ -451,7 +451,7 @@ export function runDoctor(root: string, nodeVersion: string = process.versions.n lines.push( ` · ${pkg} ${installedMajor(root, pkg)} runs its own test mode under Vitest, so no preset replaces it`, ); - } else if (!autoDetectedPresetApplies(preset, decision.engine, undefined, root)) { + } else if (!autoDetectedPresetApplies(preset, decision.engine)) { lines.push( ` · ${pkg} runs as itself under the native engine, on its native-module mocks; ` + `the ${preset} preset applies under the mock engine or with \`presets: { ${preset}: true }\``, diff --git a/packages/vitest-native/src/cli/manifest.ts b/packages/vitest-native/src/cli/manifest.ts index bc6933493..96ff1d655 100644 --- a/packages/vitest-native/src/cli/manifest.ts +++ b/packages/vitest-native/src/cli/manifest.ts @@ -60,8 +60,7 @@ export function activePresets( ): PresetName[] { const active = new Set(); for (const [pkg, preset] of Object.entries(AUTO_DETECT_PRESETS)) { - if (disabled.includes(preset) || !autoDetectedPresetApplies(preset, engine, undefined, root)) - continue; + if (disabled.includes(preset) || !autoDetectedPresetApplies(preset, engine)) continue; if (installedManifest(root, pkg) && !installedTestsItself(root, pkg)) active.add(preset); } return [...active]; diff --git a/packages/vitest-native/src/helpers.ts b/packages/vitest-native/src/helpers.ts index f4ed92062..791f60682 100644 --- a/packages/vitest-native/src/helpers.ts +++ b/packages/vitest-native/src/helpers.ts @@ -80,6 +80,21 @@ export function setInsets(insets: { const safeArea = presetMocks?.["react-native-safe-area-context"]; if (safeArea?._setInsets) { safeArea._setInsets(insets); + return; + } + // The library's own mock (the native engine): `useSafeAreaInsets` is a mock + // function whose implementation reads the provider's metrics; this answers with the + // given insets over what it answers, until resetAllMocks() returns it to the mock's own. + const hook = safeArea?.useSafeAreaInsets; + if ( + typeof hook?.mockImplementation === "function" && + typeof hook.getMockImplementation === "function" + ) { + const current = hook.getMockImplementation(); + hook.mockImplementation((...args: unknown[]) => ({ + ...(current ? current(...args) : { top: 0, right: 0, bottom: 0, left: 0 }), + ...insets, + })); } } diff --git a/packages/vitest-native/src/native/match.mjs b/packages/vitest-native/src/native/match.mjs index dcc2292cc..14caeb97f 100644 --- a/packages/vitest-native/src/native/match.mjs +++ b/packages/vitest-native/src/native/match.mjs @@ -212,7 +212,11 @@ const UTILITY_SUBPATH_LEAVES = new Set(["jest-utils", "jestSetup", "mock", "plug export function isUtilitySubpath(specifier) { const leaf = subpathLeafOf(specifier); - return leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf); + if (leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf)) return true; + // A package's `jest/` directory is its test tooling (react-native-worklets' + // jest/resolver.js, which reanimated's own resolver requires by name). + const pkg = packageNameOf(specifier); + return pkg !== specifier && specifier.slice(pkg.length + 1).split("/")[0] === "jest"; } // The preset package a RESOLVED file belongs to, when the import that reached it came diff --git a/packages/vitest-native/src/plugin.ts b/packages/vitest-native/src/plugin.ts index dedceea0a..ce7f586d3 100644 --- a/packages/vitest-native/src/plugin.ts +++ b/packages/vitest-native/src/plugin.ts @@ -484,8 +484,7 @@ async function resolveOptions( const detected = await autoDetectPresets(diagnostics, root); const disabled = disabledPresetNames(options.presets); builtIn = detected.filter( - (p) => - !disabled.has(p.name) && autoDetectedPresetApplies(p.name, engine, options.presets, root), + (p) => !disabled.has(p.name) && autoDetectedPresetApplies(p.name, engine, options.presets), ); } const presets = [...builtIn, ...(await loadPresetModules(modulePaths, root))]; @@ -681,7 +680,10 @@ const UTILITY_SUBPATH_LEAVES = new Set(["jest-utils", "jestSetup", "mock", "plug function isUtilitySubpath(specifier: string): boolean { const leaf = subpathLeafOf(specifier); - return leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf); + if (leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf)) return true; + // A package's `jest/` directory is its test tooling, as in native/match.mjs. + const pkg = packageNameOf(specifier); + return pkg !== specifier && specifier.slice(pkg.length + 1).split("/")[0] === "jest"; } /** Check if a value (or any nested value) contains functions. */ @@ -1707,8 +1709,7 @@ export function reactNative(options?: VitestNativeOptions): Plugin { ? selection.listed.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics).filter( (n) => - !disabledNative.has(n) && - autoDetectedPresetApplies(n, "native", options?.presets, resolvedRoot), + !disabledNative.has(n) && autoDetectedPresetApplies(n, "native", options?.presets), ); if (nativePresetNames.length > 0) { env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames); diff --git a/packages/vitest-native/src/preset-map.ts b/packages/vitest-native/src/preset-map.ts index 04a9cb4ed..67cdbe621 100644 --- a/packages/vitest-native/src/preset-map.ts +++ b/packages/vitest-native/src/preset-map.ts @@ -76,15 +76,11 @@ export const SELF_TESTING_FROM_MAJOR: Partial boolean>> = { - worklets: (root) => shipsJestResolver(root, "react-native-worklets"), -}; - /** * Whether an auto-detected preset applies under `engine`, given the `presets` option: * every one under the mock engine, and under the native engine all but those in - * NATIVE_ENGINE_RUNS_PACKAGES, unless the option turns one on (`{ expo: true }`). Under - * the native engine worklets' preset steps aside only when the installed worklets ships - * its Jest resolver, which needs `projectRoot`; without one it applies. + * NATIVE_ENGINE_RUNS_PACKAGES, unless the option turns one on (`{ expo: true }`). */ export function autoDetectedPresetApplies( preset: string, engine: "mock" | "native", presetsOption?: unknown, - projectRoot?: string, ): boolean { if (engine === "mock" || !(NATIVE_ENGINE_RUNS_PACKAGES as readonly string[]).includes(preset)) { return true; } - const runsWhen = RUNS_UNDER_NATIVE_WHEN[preset]; - if (runsWhen && (projectRoot === undefined || !runsWhen(projectRoot))) return true; return ( presetsOption !== null && typeof presetsOption === "object" && diff --git a/packages/vitest-native/src/presets/bottom-sheet.ts b/packages/vitest-native/src/presets/bottom-sheet.ts index d65c36e12..9c8213d43 100644 --- a/packages/vitest-native/src/presets/bottom-sheet.ts +++ b/packages/vitest-native/src/presets/bottom-sheet.ts @@ -10,6 +10,17 @@ import { createTouchableOpacityMock } from "../mocks/components/TouchableOpacity import { createTouchableHighlightMock } from "../mocks/components/TouchableHighlight.js"; import { createTouchableWithoutFeedbackMock } from "../mocks/components/TouchableWithoutFeedback.js"; import { builtInPreset } from "./built-in.js"; +import { libraryMockModule, type LibraryMock } from "./library-mock.js"; + +// Under the native engine the module is bottom-sheet's own Jest mock +// (`@gorhom/bottom-sheet/mock`), as a Jest suite installs it with +// `jest.mock('@gorhom/bottom-sheet', () => require('@gorhom/bottom-sheet/mock'))`. +// Under the mock engine, and for a version without that mock, the module below serves. +const BOTTOM_SHEET_MOCK: LibraryMock = { + pkg: "@gorhom/bottom-sheet", + entry: "mock", + file: "mock.js", +}; // @gorhom/bottom-sheet renders through reanimated worklets + gesture-handler // natives that can't run in Node. Shadow it after the library's own @@ -22,7 +33,7 @@ export function bottomSheet(): Preset { return builtInPreset({ name: "bottomSheet", modules: { - "@gorhom/bottom-sheet": { + "@gorhom/bottom-sheet": libraryMockModule(BOTTOM_SHEET_MOCK, { exports: [ "BottomSheetModal", "BottomSheetModalProvider", @@ -157,7 +168,7 @@ export function bottomSheet(): Preset { ...constants, }; }, - }, + }), }, }); } diff --git a/packages/vitest-native/src/presets/keyboard-controller.ts b/packages/vitest-native/src/presets/keyboard-controller.ts index d033bb862..d75811294 100644 --- a/packages/vitest-native/src/presets/keyboard-controller.ts +++ b/packages/vitest-native/src/presets/keyboard-controller.ts @@ -4,6 +4,17 @@ import React from "react"; import { createViewMock } from "../mocks/components/View.js"; import { createScrollViewMock } from "../mocks/components/ScrollView.js"; import { builtInPreset } from "./built-in.js"; +import { libraryMockModule, type LibraryMock } from "./library-mock.js"; + +// Under the native engine the module is keyboard-controller's own Jest mock +// (`react-native-keyboard-controller/jest`), as a Jest suite installs it: its hooks +// return React Native `Animated.Value`s and are mock functions. Under the mock engine, +// and for a version without that mock, the module below serves. +const KEYBOARD_CONTROLLER_MOCK: LibraryMock = { + pkg: "react-native-keyboard-controller", + entry: "jest", + file: "jest/index.js", +}; // react-native-keyboard-controller drives keyboard animation through native // modules + worklets that can't run in Node. Shadow it the way its own @@ -14,7 +25,7 @@ export function keyboardController(): Preset { return builtInPreset({ name: "keyboardController", modules: { - "react-native-keyboard-controller": { + "react-native-keyboard-controller": libraryMockModule(KEYBOARD_CONTROLLER_MOCK, { exports: [ "KeyboardProvider", "KeyboardControllerView", @@ -161,7 +172,7 @@ export function keyboardController(): Preset { useWindowDimensions: () => ({ width: 390, height: 844, scale: 3, fontScale: 1 }), }; }, - }, + }), }, }); } diff --git a/packages/vitest-native/src/presets/library-mock.ts b/packages/vitest-native/src/presets/library-mock.ts new file mode 100644 index 000000000..eb3f5b49a --- /dev/null +++ b/packages/vitest-native/src/presets/library-mock.ts @@ -0,0 +1,97 @@ +import fs from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import type { PresetModule } from "../types.js"; +import { mockModuleExportNames } from "./esm-export-names.js"; + +// A preset module that is the library's own test mock under the native engine. +// +// Libraries publish a mock for Jest suites to install with +// `jest.mock(pkg, () => require('/'))` (react-native-reanimated/mock, +// react-native-worklets' lib/module/mock.js, react-native-safe-area-context/jest/mock). +// Under the native engine the preset's module is that mock, loaded as Node loads any +// module, so it runs with the library's own test support around it +// (native/library-jest.mjs gives its files Jest's `jest`), and its named exports are +// read from the installed file. Where the native engine cannot run it (the library +// predates its mock, or its prerequisites), and under the mock engine, which has no +// real React Native for a mock that loads the real package, the preset's own module +// serves. + +export interface LibraryMock { + /** The package the preset shadows. */ + pkg: string; + /** The mock's path inside the package, as `require` takes it ("mock", "jest/mock"). */ + entry: string; + /** Its built file inside the package, which its export names are read from. */ + file: string; + /** Further files whose names the mock module also provides (reanimated's mock-svg). */ + alsoFiles?: string[]; + /** The export the mock module is, when it is not the whole module ("default"). */ + exportKey?: string; + /** Whether the installed package can run its mock here; by default, whether `file` exists. */ + available?: (packageDir: string, projectRoot: string) => boolean; +} + +/** Whether this test run is under the native engine (its setup installs the control). */ +function underNativeEngine(): boolean { + return ( + (globalThis as { __vitest_native_control?: { engine?: string } }).__vitest_native_control + ?.engine === "native" + ); +} + +/** The project root in a test worker, where the plugin sets it. */ +function workerRoot(): string { + return process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd(); +} + +/** The installed package's directory, from `root`, or null. */ +function packageDir(pkg: string, root: string): string | null { + // On disk, up the node_modules directories: through require(), a preset's require() + // bridge in a mock-engine worker answers for the package. + for (let dir = path.resolve(root); ; dir = path.dirname(dir)) { + const candidate = path.join(dir, "node_modules", pkg); + if (fs.existsSync(path.join(candidate, "package.json"))) return fs.realpathSync(candidate); + if (path.dirname(dir) === dir) return null; + } +} + +function usable(mock: LibraryMock, root: string): string | null { + const dir = packageDir(mock.pkg, root); + if (!dir) return null; + const available = mock.available ?? ((d: string) => fs.existsSync(path.join(d, mock.file))); + return available(dir, root) ? dir : null; +} + +/** + * `fallback`, except under the native engine where the library's own mock can run: + * there the module is the mock, with the mock's export names. + */ +export function libraryMockModule(mock: LibraryMock, fallback: PresetModule): PresetModule { + return { + exports: fallback.exports, + exportsFor(context) { + if (context.engine === "native") { + const dir = usable(mock, context.projectRoot); + if (dir) { + const names = new Set(mockModuleExportNames(path.join(dir, mock.file))); + for (const file of mock.alsoFiles ?? []) { + const full = path.join(dir, file); + if (fs.existsSync(full)) + for (const name of mockModuleExportNames(full)) names.add(name); + } + return [...names].sort(); + } + } + return fallback.exportsFor ? fallback.exportsFor(context) : fallback.exports; + }, + factory() { + const root = workerRoot(); + if (underNativeEngine() && usable(mock, root)) { + const loaded = createRequire(path.join(root, "package.json"))(`${mock.pkg}/${mock.entry}`); + return mock.exportKey ? loaded[mock.exportKey] : loaded; + } + return fallback.factory(); + }, + }; +} diff --git a/packages/vitest-native/src/presets/netinfo.ts b/packages/vitest-native/src/presets/netinfo.ts index 140e22d22..76714b218 100644 --- a/packages/vitest-native/src/presets/netinfo.ts +++ b/packages/vitest-native/src/presets/netinfo.ts @@ -1,6 +1,16 @@ import type { Preset } from "../types.js"; import { vi } from "vitest"; import { builtInPreset } from "./built-in.js"; +import { libraryMockModule, type LibraryMock } from "./library-mock.js"; + +// Under the native engine the module is netinfo's own Jest mock +// (`jest/netinfo-mock.js`), as a Jest suite installs it. Under the mock engine, and for +// a version without that mock, the module below serves. +const NETINFO_MOCK: LibraryMock = { + pkg: "@react-native-community/netinfo", + entry: "jest/netinfo-mock.js", + file: "jest/netinfo-mock.js", +}; /** * The state every fetch/listener resolves to until a test changes it. @@ -38,7 +48,7 @@ export function netInfo(): Preset { return builtInPreset({ name: "netInfo", modules: { - "@react-native-community/netinfo": { + "@react-native-community/netinfo": libraryMockModule(NETINFO_MOCK, { // Exactly the runtime surface: the six functions the entry exports, plus the // two enums re-exported through `export * from './internal/types'`. The rest // of that module is types, which have no runtime binding — declaring one @@ -122,7 +132,7 @@ export function netInfo(): Preset { }, }; }, - }, + }), }, }); } diff --git a/packages/vitest-native/src/presets/reanimated.ts b/packages/vitest-native/src/presets/reanimated.ts index 04b434121..ff9a2028a 100644 --- a/packages/vitest-native/src/presets/reanimated.ts +++ b/packages/vitest-native/src/presets/reanimated.ts @@ -5,7 +5,7 @@ import { createRequire } from "node:module"; import path from "node:path"; import { VitestNativeError } from "../errors.mjs"; import { builtInPreset } from "./built-in.js"; -import { mockModuleExportNames } from "./esm-export-names.js"; +import { libraryMockModule, type LibraryMock } from "./library-mock.js"; import { shipsJestResolver } from "../preset-map.js"; // Under the native engine the module is reanimated's own test mock @@ -17,56 +17,22 @@ import { shipsJestResolver } from "../preset-map.js"; // with an older one installed, and under the mock engine, which has no real React // Native for the real package to run on, the module below serves. -/** Whether this test run is under the native engine (its setup installs the control). */ -function underNativeEngine(): boolean { - return ( - (globalThis as { __vitest_native_control?: { engine?: string } }).__vitest_native_control - ?.engine === "native" - ); -} - -/** The installed reanimated's directory, from `root`, or null. */ -function reanimatedDir(root: string): string | null { - try { - return path.dirname( - createRequire(path.join(root, "package.json")).resolve( - "react-native-reanimated/package.json", - ), - ); - } catch { - return null; - } -} - /** - * Whether reanimated's own mock can run for `projectRoot`: it loads the real package, - * whose JS implementation loads only through reanimated's and worklets' Jest resolvers - * (reanimated 4.7, worklets 0.9). Before those, the real package's `.native` initializers - * throw, and the module below serves instead, as under the mock engine. + * Whether reanimated's own mock can run: it loads the real package, whose JS + * implementation loads only through reanimated's and worklets' Jest resolvers + * (reanimated 4.7, worklets 0.9). Before those, the real package's `.native` + * initializers throw, and the module below serves instead, as under the mock engine. */ -function libraryMockUsable(projectRoot: string): boolean { - const dir = reanimatedDir(projectRoot); - return ( - dir !== null && - shipsJestResolver(projectRoot, "react-native-reanimated") && - shipsJestResolver(dir, "react-native-worklets") - ); -} - -/** The names reanimated's own mock provides, read from the installed package. */ -function libraryMockNames(projectRoot: string): string[] | null { - const dir = reanimatedDir(projectRoot); - if (!dir) return null; - const names = new Set(mockModuleExportNames(path.join(dir, "lib/module/mock.js"))); +const REANIMATED_MOCK: LibraryMock = { + pkg: "react-native-reanimated", + entry: "mock", + file: "lib/module/mock.js", // mock.js spreads mock-svg's names over the core mock. - const svg = path.join(dir, "lib/module/mock-svg.js"); - try { - for (const name of mockModuleExportNames(svg)) names.add(name); - } catch { - // Not every version ships it. - } - return [...names].sort(); -} + alsoFiles: ["lib/module/mock-svg.js"], + available: (dir, root) => + shipsJestResolver(root, "react-native-reanimated") && + shipsJestResolver(dir, "react-native-worklets"), +}; /** * Resolve the *active* React Native module — the mock under `engine: 'mock'` @@ -90,7 +56,7 @@ export function reanimated(): Preset { return builtInPreset({ name: "reanimated", modules: { - "react-native-reanimated": { + "react-native-reanimated": libraryMockModule(REANIMATED_MOCK, { exports: [ "useSharedValue", "useAnimatedStyle", @@ -183,16 +149,7 @@ export function reanimated(): Preset { "ReduceMotion", "KeyboardState", ], - exportsFor(context) { - return context.engine === "native" && libraryMockUsable(context.projectRoot) - ? libraryMockNames(context.projectRoot) - : this.exports; - }, factory: () => { - const root = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd(); - if (underNativeEngine() && libraryMockUsable(root)) { - return createRequire(path.join(root, "package.json"))("react-native-reanimated/mock"); - } function createSharedValue(init: any) { const listeners = new Map(); const sv = { @@ -495,7 +452,7 @@ export function reanimated(): Preset { KeyboardState: { UNKNOWN: 0, OPENING: 1, OPEN: 2, CLOSING: 3, CLOSED: 4 }, }; }, - }, + }), }, }); } diff --git a/packages/vitest-native/src/presets/safe-area.ts b/packages/vitest-native/src/presets/safe-area.ts index a42ed804e..29bd52e58 100644 --- a/packages/vitest-native/src/presets/safe-area.ts +++ b/packages/vitest-native/src/presets/safe-area.ts @@ -2,12 +2,26 @@ import type { Preset } from "../types.js"; import { vi } from "vitest"; import React from "react"; import { builtInPreset } from "./built-in.js"; +import { libraryMockModule, type LibraryMock } from "./library-mock.js"; + +// Under the native engine the module is safe-area-context's own Jest mock +// (`react-native-safe-area-context/jest/mock`, its default export), as a Jest suite +// installs it: the real package, with `useSafeAreaInsets` and `useSafeAreaFrame` as +// mock functions that read the provider's metrics (``) +// and zero insets on a 320x640 frame otherwise. Under the mock engine, and for a +// version without that mock, the module below serves. +const SAFE_AREA_MOCK: LibraryMock = { + pkg: "react-native-safe-area-context", + entry: "jest/mock", + file: "lib/module/jest/mock.js", + exportKey: "default", +}; export function safeAreaContext(): Preset { return builtInPreset({ name: "safeAreaContext", modules: { - "react-native-safe-area-context": { + "react-native-safe-area-context": libraryMockModule(SAFE_AREA_MOCK, { exports: [ "SafeAreaProvider", "SafeAreaView", @@ -100,7 +114,7 @@ export function safeAreaContext(): Preset { }, }; }, - }, + }), }, }); } diff --git a/packages/vitest-native/src/presets/worklets.ts b/packages/vitest-native/src/presets/worklets.ts index f04fbcea7..38430b64b 100644 --- a/packages/vitest-native/src/presets/worklets.ts +++ b/packages/vitest-native/src/presets/worklets.ts @@ -1,17 +1,27 @@ import type { Preset } from "../types.js"; import { builtInPreset } from "./built-in.js"; +import { libraryMockModule, type LibraryMock } from "./library-mock.js"; -// react-native-worklets is reanimated's low-level runtime (and is imported -// directly by apps, e.g. `import { scheduleOnUI } from 'react-native-worklets'`). -// It ships a Jest mock at `react-native-worklets/lib/module/mock`, but that file -// is ESM that ends with `module.exports = …`; under the native engine RN and its -// ecosystem are externalized, so requiring it through Node throws "module is not -// defined in ES module scope" and takes down the whole test file. +const WORKLETS_MOCK: LibraryMock = { + pkg: "react-native-worklets", + entry: "lib/module/mock.js", + file: "lib/module/mock.js", +}; + +// react-native-worklets is reanimated's low-level runtime (and is imported directly +// by apps, e.g. `import { scheduleOnUI } from 'react-native-worklets'`). +// +// Under the native engine the module is worklets' own Jest mock +// (`lib/module/mock.js`), as a Jest suite installs it with +// `jest.mock('react-native-worklets', () => require('react-native-worklets/lib/module/mock'))`. +// A suite has to: with react-native-gesture-handler 3, the real package's JS +// implementation throws "`getUIRuntimeHolder` is not supported on web" in every test +// file, under Jest as here, because gesture-handler's reanimated wrapper calls it in a +// microtask. Reanimated's own mock runs over worklets' mock. // -// This preset shadows the package with a self-contained mock modelled on -// worklets' own `mock.js` WorkletAPI. Schedulers run their worklet synchronously -// (matching the reanimated preset's `runOnJS`/`runOnUI => fn` convention) so -// UI-thread work is observable in tests without fake-timer juggling. +// Under the mock engine, and for a worklets without that mock, the module below +// serves: a self-contained mock modelled on worklets' own WorkletAPI, whose schedulers +// run their worklet synchronously, as worklets' mock does. // Mirrors worklets' RuntimeKind enum (lib/module/runtimeKind.js). Tests run on // the React Native runtime. @@ -25,7 +35,7 @@ export function worklets(): Preset { return builtInPreset({ name: "worklets", modules: { - "react-native-worklets": { + "react-native-worklets": libraryMockModule(WORKLETS_MOCK, { exports: [ "runOnJS", "runOnUI", @@ -132,7 +142,7 @@ export function worklets(): Preset { api.default = api; return api; }, - }, + }), }, }); } diff --git a/packages/vitest-native/tests-native/jest-registry-require-actual.test.ts b/packages/vitest-native/tests-native/jest-registry-require-actual.test.ts index 50f9ddee0..bfea4fd67 100644 --- a/packages/vitest-native/tests-native/jest-registry-require-actual.test.ts +++ b/packages/vitest-native/tests-native/jest-registry-require-actual.test.ts @@ -9,7 +9,7 @@ * too. Under Vitest the variant loads through Node, where no mock applied, so it read * the REAL storage. */ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { kind, sessionId } from "@vn-app/registry/session"; declare const jest: { @@ -60,12 +60,14 @@ describe("require() from a test file", () => { describe("jest.requireActual of a package a preset shadows", () => { it("is the package, not the preset", () => { - // The safe-area-context preset shadows the package by name; Jest's requireActual - // gives the real one, which a library's own mock spreads (its jest/mock does). + // The safe-area-context preset shadows the package by name (its module is the + // library's own mock, whose hooks are mock functions); Jest's requireActual gives + // the real package, whose hooks are not. const actual = jest.requireActual>("react-native-safe-area-context"); const shadowed = jest.requireMock>("react-native-safe-area-context"); - expect(typeof actual.SafeAreaListener).toBe("function"); - expect(shadowed.SafeAreaListener).toBeUndefined(); + expect(vi.isMockFunction(shadowed.useSafeAreaInsets)).toBe(true); + expect(typeof actual.useSafeAreaInsets).toBe("function"); + expect(vi.isMockFunction(actual.useSafeAreaInsets)).toBe(false); // Only that load: the next one by name is the preset again. expect(jest.requireMock>("react-native-safe-area-context")).toBe( shadowed, diff --git a/packages/vitest-native/tests-native/third-party-presets.test.tsx b/packages/vitest-native/tests-native/third-party-presets.test.tsx index 8ee14b043..37f0e2c92 100644 --- a/packages/vitest-native/tests-native/third-party-presets.test.tsx +++ b/packages/vitest-native/tests-native/third-party-presets.test.tsx @@ -66,8 +66,10 @@ describe("@gorhom/bottom-sheet under native engine", () => { , ); - expect(screen.getByTestId("sheet")).toBeTruthy(); + // bottom-sheet's own mock (mock.js) renders a view's children and nothing of its + // own, as under Jest, so the content is there and the view's testID is not. expect(screen.getByText("sheet content")).toBeTruthy(); + expect(screen.queryByTestId("sheet")).toBeNull(); }); it("the constant enums are shadowed, not undefined", () => { diff --git a/packages/vitest-native/tests-native/third-party-stack.test.tsx b/packages/vitest-native/tests-native/third-party-stack.test.tsx index e4e228894..49bb10a53 100644 --- a/packages/vitest-native/tests-native/third-party-stack.test.tsx +++ b/packages/vitest-native/tests-native/third-party-stack.test.tsx @@ -17,11 +17,7 @@ import { Gesture, State, } from "react-native-gesture-handler"; -import { - SafeAreaProvider, - SafeAreaView, - useSafeAreaInsets, -} from "react-native-safe-area-context"; +import { SafeAreaProvider, SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context"; import { NavigationContainer, useNavigation } from "@react-navigation/native"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; @@ -51,7 +47,9 @@ describe("react-native-safe-area-context under native engine", () => { return top:{insets.top}; } - it("SafeAreaProvider/SafeAreaView render and useSafeAreaInsets returns mock insets", async () => { + // The library's own Jest mock (jest/mock): zero insets on a 320x640 frame, unless the + // provider is given metrics, as its testing guide sets them up. + it("SafeAreaProvider/SafeAreaView render and useSafeAreaInsets returns the mock's insets", async () => { await render( @@ -60,6 +58,20 @@ describe("react-native-safe-area-context under native engine", () => { , ); expect(screen.getByTestId("sa-view")).toBeTruthy(); + expect(screen.getByText("top:0")).toBeTruthy(); + }); + + it("reads the metrics a test gives SafeAreaProvider", async () => { + await render( + + + , + ); expect(screen.getByText("top:47")).toBeTruthy(); }); }); diff --git a/packages/vitest-native/tests/migrate-discovery.test.ts b/packages/vitest-native/tests/migrate-discovery.test.ts index 8959ef551..5555aa983 100644 --- a/packages/vitest-native/tests/migrate-discovery.test.ts +++ b/packages/vitest-native/tests/migrate-discovery.test.ts @@ -551,27 +551,6 @@ describe("a jest-expo app's package.json#jest", () => { expect(doctor).toContain("⚠ @lingui/babel-plugin-lingui-macro compiles macro imports away"); }); - it("judges the worklets plugin unneeded where worklets runs as itself, by its Jest resolver", () => { - const worklets = (withResolver: boolean) => - blueskyLike({ - "node_modules/react-native-worklets/package.json": { - name: "react-native-worklets", - version: withResolver ? "0.13.0" : "0.5.1", - }, - ...(withResolver ? { "node_modules/react-native-worklets/jest/resolver.js": "" } : {}), - }); - const verdict = (root: string) => - classifyBabelPlugins(readBabelConfig(root), root, []).find( - (p) => p.name === "react-native-worklets/plugin", - ); - const runsItself = verdict(worklets(true)); - expect(runsItself?.verdict).toBe("unneeded"); - expect(runsItself?.reason).toContain("runs as itself under the native engine"); - // Before worklets 0.9 there is no resolver, its preset applies, and here it is not - // active, so the plugin is left to judge. - expect(verdict(worklets(false))?.verdict).toBe("unknown"); - }); - it("emits the Babel plugin when Vite 8 and @rolldown/plugin-babel are installed", () => { const report = analyzeJestConfig( blueskyLike({ diff --git a/packages/vitest-native/tests/preset-engine.test.ts b/packages/vitest-native/tests/preset-engine.test.ts index 3ac4e9cef..d29b624a5 100644 --- a/packages/vitest-native/tests/preset-engine.test.ts +++ b/packages/vitest-native/tests/preset-engine.test.ts @@ -12,28 +12,13 @@ import { activePresets } from "../src/cli/manifest.js"; import { autoDetectedPresetApplies, NATIVE_ENGINE_RUNS_PACKAGES } from "../src/preset-map.js"; describe("autoDetectedPresetApplies", () => { - it("steps the expo and worklets presets aside under the native engine only", () => { - expect(NATIVE_ENGINE_RUNS_PACKAGES).toEqual(["expo", "worklets"]); - // This package installs react-native-worklets 0.13, which ships its Jest resolver. - const root = path.resolve(import.meta.dirname, ".."); - for (const preset of ["expo", "worklets"]) { - expect(autoDetectedPresetApplies(preset, "native", undefined, root)).toBe(false); - expect(autoDetectedPresetApplies(preset, "mock", undefined, root)).toBe(true); - } - // Reanimated's applies, with reanimated's own mock as its module there. - expect(autoDetectedPresetApplies("reanimated", "native", undefined, root)).toBe(true); - }); - - it("keeps the worklets preset where the installed worklets has no Jest resolver", () => { - // Before worklets 0.9 its `.native` initializers load and throw without one. - const bare = fs.mkdtempSync(path.join(os.tmpdir(), "vn-no-resolver-")); - try { - fs.writeFileSync(path.join(bare, "package.json"), "{}"); - expect(autoDetectedPresetApplies("worklets", "native", undefined, bare)).toBe(true); - expect(autoDetectedPresetApplies("worklets", "native")).toBe(true); - expect(autoDetectedPresetApplies("expo", "native", undefined, bare)).toBe(false); - } finally { - fs.rmSync(bare, { recursive: true, force: true }); + it("steps the expo preset aside under the native engine only", () => { + expect(NATIVE_ENGINE_RUNS_PACKAGES).toEqual(["expo"]); + expect(autoDetectedPresetApplies("expo", "native")).toBe(false); + expect(autoDetectedPresetApplies("expo", "mock")).toBe(true); + // These apply, with the library's own mock as their module there. + for (const preset of ["reanimated", "worklets", "safeAreaContext"]) { + expect(autoDetectedPresetApplies(preset, "native")).toBe(true); } }); diff --git a/packages/vitest-native/tests/preset-library-mocks.test.ts b/packages/vitest-native/tests/preset-library-mocks.test.ts index 40d34fbce..83d734a4d 100644 --- a/packages/vitest-native/tests/preset-library-mocks.test.ts +++ b/packages/vitest-native/tests/preset-library-mocks.test.ts @@ -281,3 +281,29 @@ describe("presets against each library's own mock", () => { }); } }); + +describe("presets that are the library's own mock under the native engine", () => { + // Reanimated's, worklets' and safe-area-context's modules there are the library's + // mocks (presets/library-mock.ts), so they provide every name the mock does. + const root = path.resolve(import.meta.dirname, ".."); + for (const name of [ + "reanimated", + "worklets", + "safe-area-context", + "keyboard-controller", + "bottom-sheet", + "netinfo", + ]) { + it(`${name} lacks nothing`, () => { + const { preset, module, reference } = CASES[name]; + const names = preset().modules[module].exportsFor?.({ + projectRoot: root, + platform: "ios", + engine: "native", + }); + expect(names).not.toBeNull(); + const missing = referenceNames(reference).filter((n) => !names!.includes(n)); + expect(missing).toEqual([]); + }); + } +}); diff --git a/packages/vitest-native/tests/preset-mock-reset.test.ts b/packages/vitest-native/tests/preset-mock-reset.test.ts index 112d8690c..bf1320f6a 100644 --- a/packages/vitest-native/tests/preset-mock-reset.test.ts +++ b/packages/vitest-native/tests/preset-mock-reset.test.ts @@ -130,6 +130,12 @@ describe("package source", () => { const EXEMPT = path.join(SRC, "jest-compat"); const SETTER = /\.mock(?:ReturnValue|ReturnThis|Implementation|ResolvedValue|RejectedValue)(?:Once)?\(/; + // Setters a reset is meant to undo, by file and the call as written. + const RESET_UNDOES = [ + // setInsets() over safe-area-context's own mock: its insets hold until + // resetAllMocks() returns `useSafeAreaInsets` to the mock's implementation. + { file: "helpers.ts", call: "hook.mockImplementation(" }, + ]; function sourceFiles(dir: string): string[] { return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { @@ -148,6 +154,12 @@ describe("package source", () => { .split("\n") .map((line, i) => ({ line, at: `${path.relative(SRC, file)}:${i + 1}` })) .filter(({ line }) => SETTER.test(line) && !/^\s*(?:\/\/|\*)/.test(line)) + .filter( + ({ line }) => + !RESET_UNDOES.some( + (allowed) => path.relative(SRC, file) === allowed.file && line.includes(allowed.call), + ), + ) .map(({ at }) => at), ); expect(offending, "use vi.fn(impl), which a reset keeps").toEqual([]); diff --git a/website/guide/helpers.md b/website/guide/helpers.md index 6ab253b36..d6db2dace 100644 --- a/website/guide/helpers.md +++ b/website/guide/helpers.md @@ -44,7 +44,7 @@ setColorScheme('dark') ## `setInsets(insets)` -Override the safe-area insets reported by the auto-detected `react-native-safe-area-context` preset (`useSafeAreaInsets`, `SafeAreaProvider`). No-op when the preset isn't active. +Override the safe-area insets reported by the auto-detected `react-native-safe-area-context` preset. Under the mock engine they reach `useSafeAreaInsets`, the insets context and `initialWindowMetrics`. Under the native engine the preset is the library's own Jest mock, and `setInsets` reaches `useSafeAreaInsets` only; to give every consumer (`SafeAreaInsetsContext`, `withSafeAreaInsets`) the same insets there, render under ``, as the library's testing guide does. No-op when the preset isn't active; undone by `resetAllMocks()`. ```ts setInsets({ top: 59, bottom: 34, left: 0, right: 0 }) diff --git a/website/guide/presets.md b/website/guide/presets.md index 553b4bb6f..8a17e7bcd 100644 --- a/website/guide/presets.md +++ b/website/guide/presets.md @@ -40,22 +40,22 @@ Presets apply under **both** engines. | 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.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` | `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.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 `` 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.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 | From 38844cc0dc759a3e6d1192fe51a8b7768b8b8768 Mon Sep 17 00:00:00 2001 From: Daniel Fry <95628792+danfry1@users.noreply.github.com> Date: Wed, 28 Oct 2026 22:45:30 +0000 Subject: [PATCH 4/4] feat(native): gesture-handler and flash-list run as themselves with their own Jest setup Their presets replaced the whole package, so gesture-handler 3's hook API, many builder methods and its own test helpers were missing, and the list rendered every row. Each library's own jestSetup.js mocks only its native layer, as under Jest; the native engine now runs it before the project's setup files, and migrate drops it from a migrated config. --- .changeset/library-test-support.md | 2 + README.md | 4 +- packages/vitest-native/README.md | 4 +- packages/vitest-native/src/cli/doctor.ts | 14 ++++- packages/vitest-native/src/cli/migrate.ts | 31 +++++++++- .../vitest-native/src/native/library-jest.mjs | 1 + packages/vitest-native/src/native/setup.mjs | 20 +++++++ packages/vitest-native/src/plugin.ts | 14 +++++ packages/vitest-native/src/preset-map.ts | 23 +++++++- .../tests-native/library-setup-files.test.tsx | 57 ++++++++++++++++++ .../preset-subpath-cross-file.test.tsx | 10 ++-- .../tests-native/preset-subpath.test.tsx | 41 +++++++------ packages/vitest-native/tests/cli.test.ts | 59 +++++++++++++++++-- .../vitest-native/tests/preset-engine.test.ts | 10 ++-- website/guide/presets.md | 4 +- 15 files changed, 249 insertions(+), 45 deletions(-) create mode 100644 packages/vitest-native/tests-native/library-setup-files.test.tsx diff --git a/.changeset/library-test-support.md b/.changeset/library-test-support.md index 5faebe565..8e8e50aa7 100644 --- a/.changeset/library-test-support.md +++ b/.changeset/library-test-support.md @@ -12,4 +12,6 @@ Under the native engine, these presets are their library's own mock, as a Jest s - `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 `` 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`; `` 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. diff --git a/README.md b/README.md index 41a4e834e..3709c3aca 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ export default defineConfig({ |--------|---------|---------------| | `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: 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` | `GestureHandlerRootView`, gesture handlers (Pan, Tap, LongPress, Pinch, Rotation, Fling), `Gesture` API (v2), `GestureDetector`, `Swipeable`, touchable wrappers, state constants | +| `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 `` 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` | @@ -248,7 +248,7 @@ export default defineConfig({ | `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.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 | diff --git a/packages/vitest-native/README.md b/packages/vitest-native/README.md index 83c97b399..75828fe43 100644 --- a/packages/vitest-native/README.md +++ b/packages/vitest-native/README.md @@ -542,7 +542,7 @@ export default defineConfig({ |--------|---------|---------------| | `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: 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` | `GestureHandlerRootView`, gesture handlers (Pan, Tap, LongPress, Pinch, Rotation, Fling), `Gesture` API (v2), `GestureDetector`, `Swipeable`, touchable wrappers, state constants | +| `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 `` 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` | @@ -554,7 +554,7 @@ export default defineConfig({ | `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.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 | diff --git a/packages/vitest-native/src/cli/doctor.ts b/packages/vitest-native/src/cli/doctor.ts index 457878dc5..f3093056b 100644 --- a/packages/vitest-native/src/cli/doctor.ts +++ b/packages/vitest-native/src/cli/doctor.ts @@ -16,7 +16,13 @@ import { } from "../native/ownership.mjs"; import { createHotMemoryPlan, formatHotMemoryPlan } from "../native/memory.mjs"; import { HOT_STATE_MANIFEST_ENTRIES } from "../native/state-manifest.mjs"; -import { AUTO_DETECT_PRESETS, PRESET_MODULES, autoDetectedPresetApplies } from "../preset-map.js"; +import { + AUTO_DETECT_PRESETS, + LIBRARY_SETUP_FILES, + PRESET_MODULES, + autoDetectedPresetApplies, + type PresetName, +} from "../preset-map.js"; import { babelRecipe, classifyBabelPlugins, readBabelConfig, viteMajor } from "./babel-config.js"; import { activePresets, @@ -452,8 +458,12 @@ export function runDoctor(root: string, nodeVersion: string = process.versions.n ` · ${pkg} ${installedMajor(root, pkg)} runs its own test mode under Vitest, so no preset replaces it`, ); } else if (!autoDetectedPresetApplies(preset, decision.engine)) { + const setupFile = LIBRARY_SETUP_FILES[preset as PresetName]; lines.push( - ` · ${pkg} runs as itself under the native engine, on its native-module mocks; ` + + ` · ${pkg} runs as itself under the native engine, ` + + (setupFile + ? `with its own Jest setup (${setupFile}); ` + : `on its native-module mocks; `) + `the ${preset} preset applies under the mock engine or with \`presets: { ${preset}: true }\``, ); } else { diff --git a/packages/vitest-native/src/cli/migrate.ts b/packages/vitest-native/src/cli/migrate.ts index b6779a8d3..b838de8c0 100644 --- a/packages/vitest-native/src/cli/migrate.ts +++ b/packages/vitest-native/src/cli/migrate.ts @@ -13,7 +13,12 @@ import { createRequire } from "node:module"; import fs from "node:fs"; import path from "node:path"; -import { DEFAULT_ASSET_EXTS, presetShadowing, type PresetName } from "../preset-map.js"; +import { + DEFAULT_ASSET_EXTS, + LIBRARY_SETUP_FILES, + presetShadowing, + type PresetName, +} from "../preset-map.js"; import { detectEcosystemPackages } from "../native/ecosystem.js"; import { allows, extractAllowlistPackages, type AllowlistEntry } from "./allowlist.js"; import { @@ -265,6 +270,10 @@ export function analyzeJestConfig(root: string): MigrationReport { // detects and compiles by itself under them. A `transform` entry for one of those // would take precedence over detection and externalize it instead. const active: PresetName[] = activePresets(root, navigationOff ? ["navigation"] : []); + // A preset that steps aside under the native engine for a library that runs as itself + // with the Jest setup file it ships (LIBRARY_SETUP_FILES). + const runsWithOwnSetup = (preset: PresetName): boolean => + LIBRARY_SETUP_FILES[preset] !== undefined && !active.includes(preset); const autoInlined = new Set(detectEcosystemPackages(root, [], [], [], active)); const addAlias = (key: string, value: string) => { @@ -338,7 +347,10 @@ export function analyzeJestConfig(root: string): MigrationReport { // A library's own test setup (react-native-unistyles/mocks, a jestSetup.js): // run under the jest-compat shim, its jest.mock() calls would replace the // preset that already shadows the package. - const setupPackage = /^(@[^/]+\/[^/]+|[^@./][^/]*)\//.exec(f)?.[1]; + // As a package request, or by path into node_modules, the form libraries' own + // docs give (`./node_modules/react-native-gesture-handler/jestSetup.js`). + const asRequest = f.replace(/^(?:\/|\.\/)?node_modules\//, ""); + const setupPackage = /^(@[^/]+\/[^/]+|[^@./<][^/]*)\//.exec(asRequest)?.[1]; const setupPreset = setupPackage ? presetShadowing(setupPackage) : undefined; if (/react-native\/jest\/setup/.test(f)) { presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`); @@ -347,6 +359,16 @@ export function analyzeJestConfig(root: string): MigrationReport { `${key}: '${f}' — ${setupPackage}'s own test setup; the auto-detected ${setupPreset} ` + `preset shadows ${setupPackage}, and this file's jest.mock() calls would replace it; delete.`, ); + } else if ( + setupPreset && + runsWithOwnSetup(setupPreset) && + // Only the file the engine runs itself; another of the package's files stays. + asRequest.replace(/\.js$/, "") === LIBRARY_SETUP_FILES[setupPreset]?.replace(/\.js$/, "") + ) { + presetCovered.push( + `${key}: '${f}' — ${setupPackage}'s own test setup, which the native engine runs ` + + `before the setup files (${LIBRARY_SETUP_FILES[setupPreset]}); delete.`, + ); } else if (/jest-expo/.test(f)) { attention.push(`${key}: '${f}' — ${expoPresetCoverage()}.`); } else if (f.startsWith("")) { @@ -705,6 +727,11 @@ export function analyzeJestConfig(root: string): MigrationReport { presetCovered.push( `__mocks__/${candidate} — the auto-detected ${preset} preset shadows ${candidate}; delete the manual mock.`, ); + } else if (preset && runsWithOwnSetup(preset) && installedManifest(root, candidate)) { + presetCovered.push( + `__mocks__/${candidate} — the native engine runs ${candidate} with its own Jest setup ` + + `(${LIBRARY_SETUP_FILES[preset]}), which replaces its native layer; delete the manual mock.`, + ); } else if (installedManifest(root, candidate) && installedTestsItself(root, candidate)) { attention.push( `__mocks__/${candidate} — ${candidate} ${installedMajor(root, candidate)} runs its own test ` + diff --git a/packages/vitest-native/src/native/library-jest.mjs b/packages/vitest-native/src/native/library-jest.mjs index 5719f74f8..3e6a121e7 100644 --- a/packages/vitest-native/src/native/library-jest.mjs +++ b/packages/vitest-native/src/native/library-jest.mjs @@ -145,6 +145,7 @@ function loaded(owner) { /** * Start a test file: of what libraries registered, only what a still-loaded support * entry made is kept (see the top of this file), and only those packages stay active. + * The engine's own library setup files run after this, for every file (setup.mjs). */ export function beginTestFile() { active.clear(); diff --git a/packages/vitest-native/src/native/setup.mjs b/packages/vitest-native/src/native/setup.mjs index 7979533a6..91b76ef96 100644 --- a/packages/vitest-native/src/native/setup.mjs +++ b/packages/vitest-native/src/native/setup.mjs @@ -296,6 +296,26 @@ installLibraryJest(vi); // Each test file keeps only what a still-loaded library support module registered, // under every pool: the hot runtime and `isolate: false` reuse a worker. beginTestFile(); +// The setup files of libraries that run as themselves (LIBRARY_SETUP_FILES in +// preset-map.ts), ahead of the project's, as a Jest suite lists them. Run afresh for +// every test file, so each file's mocks are new ones, as under Jest. +let librarySetupFiles = []; +try { + librarySetupFiles = JSON.parse(process.env.VITEST_NATIVE_LIBRARY_SETUP_FILES || "[]"); +} catch { + librarySetupFiles = []; +} +for (const request of librarySetupFiles) { + const load = createRequire(path.join(projectRoot, "package.json")); + let file; + try { + file = load.resolve(request); + } catch { + continue; // not installed in this project + } + delete load.cache[file]; + load(request); +} // Through Vitest, so a TypeScript preset module loads. Its export lists already // reached the ESM loader from the plugin; a module the plugin did not read would be // served by the real package there. diff --git a/packages/vitest-native/src/plugin.ts b/packages/vitest-native/src/plugin.ts index ce7f586d3..d6d1e249a 100644 --- a/packages/vitest-native/src/plugin.ts +++ b/packages/vitest-native/src/plugin.ts @@ -75,6 +75,8 @@ import { PRESET_MODULES, presetForInstalled, autoDetectedPresetApplies, + LIBRARY_SETUP_FILES, + type PresetName, } from "./preset-map.js"; async function autoDetectPresets(diagnostics: boolean, projectRoot: string): Promise { @@ -1714,6 +1716,18 @@ export function reactNative(options?: VitestNativeOptions): Plugin { if (nativePresetNames.length > 0) { env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames); } + // The Jest setup files of installed libraries whose preset steps aside here and + // that run as themselves (LIBRARY_SETUP_FILES), for the native setup file to + // run ahead of the project's own. + if (!selection.listed) { + const librarySetupFiles = autoDetectPresetNames(resolvedRoot, diagnostics) + .filter((n) => !disabledNative.has(n) && !nativePresetNames.includes(n)) + .map((n) => LIBRARY_SETUP_FILES[n as PresetName]) + .filter((file): file is string => typeof file === "string"); + if (librarySetupFiles.length > 0) { + env.VITEST_NATIVE_LIBRARY_SETUP_FILES = JSON.stringify(librarySetupFiles); + } + } if (selection.modulePaths.length > 0) { env.VITEST_NATIVE_PRESET_MODULES = JSON.stringify(selection.modulePaths); } diff --git a/packages/vitest-native/src/preset-map.ts b/packages/vitest-native/src/preset-map.ts index 67cdbe621..595a42019 100644 --- a/packages/vitest-native/src/preset-map.ts +++ b/packages/vitest-native/src/preset-map.ts @@ -69,6 +69,10 @@ export const SELF_TESTING_FROM_MAJOR: Partial>> = { + gestureHandler: "react-native-gesture-handler/jestSetup.js", + flashList: "@shopify/flash-list/jestSetup.js", +}; /** * Whether `pkg`, resolved from `projectRoot`, ships the Jest resolver its JS diff --git a/packages/vitest-native/tests-native/library-setup-files.test.tsx b/packages/vitest-native/tests-native/library-setup-files.test.tsx new file mode 100644 index 000000000..f8c7b4fa0 --- /dev/null +++ b/packages/vitest-native/tests-native/library-setup-files.test.tsx @@ -0,0 +1,57 @@ +/** + * Libraries whose own Jest support is a setup file run as themselves under the native + * engine, with that file run first (LIBRARY_SETUP_FILES in preset-map.ts), as a Jest + * suite lists it in `setupFiles`. Each replaces only the library's native layer. + */ +import React from "react"; +import { act, fireEvent, render, screen } from "@testing-library/react-native"; +import { Text } from "react-native"; +import * as GH from "react-native-gesture-handler"; +import { FlashList } from "@shopify/flash-list"; +import { describe, expect, it, vi } from "vitest"; + +describe("react-native-gesture-handler, with its jestSetup", () => { + it("is the real package: gesture-handler 3's hook API and builder methods", () => { + expect(typeof (GH as Record).usePanGesture).toBe("function"); + expect(typeof GH.Gesture.Pan().onBegin).toBe("function"); + }); + + it("presses a Pressable through its own mocks", async () => { + let presses = 0; + await render( + + presses++}> + go + + , + ); + fireEvent.press(screen.getByTestId("press")); + expect(presses).toBe(1); + }); +}); + +describe("@shopify/flash-list, with its jestSetup", () => { + const rows = () => Array.from({ length: 200 }, (_, i) => i); + const rendered = () => rows().filter((i) => screen.queryByText(`row ${i}`)).length; + const list = () => ( + {`row ${item}`}} /> + ); + + // jestSetup measures the list 400x900 and each row 100x100. FlashList then renders a + // window and fills it in on a later frame: 10 rows, then 15, as under Jest with the + // same setup. Without the setup's measurements every one of the 200 rows rendered. + const settled = async () => { + await render(list()); + await act(() => new Promise((resolve) => setTimeout(resolve, 100))); + return rendered(); + }; + + it("renders a window of rows over the layout its setup measures, as under Jest", async () => { + expect(await settled()).toBe(15); + }); + + it("keeps that layout through vi.resetAllMocks()", async () => { + vi.resetAllMocks(); + expect(await settled()).toBe(15); + }); +}); diff --git a/packages/vitest-native/tests-native/preset-subpath-cross-file.test.tsx b/packages/vitest-native/tests-native/preset-subpath-cross-file.test.tsx index ec5d4c6af..e860ced72 100644 --- a/packages/vitest-native/tests-native/preset-subpath-cross-file.test.tsx +++ b/packages/vitest-native/tests-native/preset-subpath-cross-file.test.tsx @@ -9,14 +9,14 @@ import { describe, it, expect } from "vitest"; describe("preset subpath identity across hot-worker files", () => { it("CJS subpath leaf is the current file's root mock export", () => { - const viaSubpath = require("react-native-gesture-handler/Swipeable"); - const root = require("react-native-gesture-handler"); - expect(viaSubpath.default).toBe(root.Swipeable); + const viaSubpath = require("react-native-safe-area-context/lib/commonjs/SafeAreaView"); + const root = require("react-native-safe-area-context"); + expect(viaSubpath.default).toBe(root.SafeAreaView); }); it("repeated requires stay identity-stable within the file", () => { - const a = require("react-native-gesture-handler/Swipeable"); - const b = require("react-native-gesture-handler/Swipeable"); + const a = require("react-native-safe-area-context/lib/commonjs/SafeAreaView"); + const b = require("react-native-safe-area-context/lib/commonjs/SafeAreaView"); expect(a).toBe(b); }); }); diff --git a/packages/vitest-native/tests-native/preset-subpath.test.tsx b/packages/vitest-native/tests-native/preset-subpath.test.tsx index 812cb07b7..b3320db19 100644 --- a/packages/vitest-native/tests-native/preset-subpath.test.tsx +++ b/packages/vitest-native/tests-native/preset-subpath.test.tsx @@ -1,9 +1,8 @@ /** - * Deep (subpath) imports of preset packages must be shadowed like the root - * import — `import Swipeable from 'react-native-gesture-handler/Swipeable'` is a - * common real-app pattern, and letting it fall through would load the package's - * real native runtime (or fail resolution entirely: RNGH 3.x no longer ships a - * /Swipeable file, so pre-3.x app code only works because of the redirect). + * Deep (subpath) imports of preset packages must be shadowed like the root import + * (`import SafeAreaView from 'react-native-safe-area-context/lib/commonjs/SafeAreaView'`): + * letting one fall through would load a second, real copy of a package the preset + * stands in for. The leaf is the root mock's export of that name. * * JSON subpaths are exempt: `require('pkg/package.json').version` gates must * read the real manifest. @@ -13,17 +12,17 @@ import React from "react"; import { render, screen } from "@testing-library/react-native"; import { Text } from "react-native"; // @ts-expect-error — no type declarations for the deep path (redirected at runtime) -import Swipeable from "react-native-gesture-handler/Swipeable"; -import { Swipeable as RootSwipeable } from "react-native-gesture-handler"; +import SubpathSafeAreaView from "react-native-safe-area-context/lib/commonjs/SafeAreaView"; +import { SafeAreaView as RootSafeAreaView } from "react-native-safe-area-context"; describe("preset subpath imports under the native engine", () => { it("ESM deep import yields the preset mock's leaf export and renders", async () => { - expect(Swipeable).toBeTruthy(); - expect(Swipeable).toBe(RootSwipeable); + expect(SubpathSafeAreaView).toBeTruthy(); + expect(SubpathSafeAreaView).toBe(RootSafeAreaView); await render( - + row content - , + , ); expect(screen.getByText("row content")).toBeTruthy(); }); @@ -32,9 +31,9 @@ describe("preset subpath imports under the native engine", () => { // runtime preset mocks are rebuilt per file, so a stale subpath cache would // surface here as an identity mismatch (see preset-subpath-cross-file twin). it("CJS subpath leaf identity matches the current root mock", () => { - const viaSubpath = require("react-native-gesture-handler/Swipeable"); - const root = require("react-native-gesture-handler"); - expect(viaSubpath.default).toBe(root.Swipeable); + const viaSubpath = require("react-native-safe-area-context/lib/commonjs/SafeAreaView"); + const root = require("react-native-safe-area-context"); + expect(viaSubpath.default).toBe(root.SafeAreaView); }); // Utility subpaths (jest-utils, jestSetup, mock, plugin) passing through to @@ -57,8 +56,8 @@ describe("preset subpath imports under the native engine", () => { }); it("CJS deep require yields the leaf with interop default, identity-stable", () => { - const a = require("react-native-gesture-handler/Swipeable"); - const b = require("react-native-gesture-handler/Swipeable"); + const a = require("react-native-safe-area-context/lib/commonjs/SafeAreaView"); + const b = require("react-native-safe-area-context/lib/commonjs/SafeAreaView"); expect(a.default).toBeTruthy(); expect(a.__esModule).toBe(true); // Memoized: repeated requires must return the same object (spies/instanceof). @@ -66,14 +65,14 @@ describe("preset subpath imports under the native engine", () => { }); it("unknown leaves fall back to the root preset mock", () => { - const mod = require("react-native-gesture-handler/lib/commonjs/whatever"); - expect(mod.State).toBeDefined(); - expect(mod.GestureHandlerRootView).toBeDefined(); + const mod = require("react-native-safe-area-context/lib/commonjs/whatever"); + expect(mod.SafeAreaProvider).toBeDefined(); + expect(mod.useSafeAreaInsets).toBeDefined(); }); it("package.json subpath reads the real manifest", () => { - const pkg = require("react-native-gesture-handler/package.json"); - expect(pkg.name).toBe("react-native-gesture-handler"); + const pkg = require("react-native-safe-area-context/package.json"); + expect(pkg.name).toBe("react-native-safe-area-context"); expect(typeof pkg.version).toBe("string"); }); }); diff --git a/packages/vitest-native/tests/cli.test.ts b/packages/vitest-native/tests/cli.test.ts index 082783408..a154d181e 100644 --- a/packages/vitest-native/tests/cli.test.ts +++ b/packages/vitest-native/tests/cli.test.ts @@ -287,15 +287,14 @@ describe("migrate", () => { expect(report.suggestedConfig).toContain("testTimeout: 15000"); // manual mock covered by preset; unknown key surfaced. expect(text).toContain( - "__mocks__/react-native-gesture-handler — the auto-detected gestureHandler preset shadows", + "__mocks__/react-native-gesture-handler — the native engine runs react-native-gesture-handler with its own Jest setup", ); expect(text).toContain("'someCustomKey' — unrecognized Jest key"); }); it("calls a manual mock covered only where an active preset shadows that module", () => { // The claim is read from PRESET_MODULES (held to the presets by - // tests/presets.test.ts) and the plugin's detection. gesture-handler's preset is - // detected and shadows the module. The expo preset is detected too, but the native + // tests/presets.test.ts) and the plugin's detection. The expo preset is detected, but the native // engine the generated config uses runs expo-font as itself // (NATIVE_ENGINE_RUNS_PACKAGES), so its manual mock stays, as does svg's, whose // preset is not detected. @@ -312,8 +311,10 @@ describe("migrate", () => { "__mocks__/react-native-svg.js": "module.exports = {};", }); const covered = analyzeJestConfig(root).presetCovered.join("\n"); + // gesture-handler runs as itself under the native engine, with its own jestSetup + // standing in for its native layer (LIBRARY_SETUP_FILES), so its manual mock goes. expect(covered).toContain( - "__mocks__/react-native-gesture-handler — the auto-detected gestureHandler preset shadows react-native-gesture-handler", + "__mocks__/react-native-gesture-handler — the native engine runs react-native-gesture-handler with its own Jest setup", ); expect(covered).not.toContain("expo-font"); expect(covered).not.toContain("react-native-svg"); @@ -343,6 +344,56 @@ describe("migrate", () => { expect(report.suggestedConfig).toContain('"some-lib/jest-setup"'); }); + it("deletes the Jest setup the native engine runs for a library, however it is written", () => { + // gesture-handler's docs give `./node_modules/react-native-gesture-handler/jestSetup.js`; + // `/node_modules/...` and the package request are as common. The engine runs + // each library's own setup itself (LIBRARY_SETUP_FILES). + const root = fixture({ + "package.json": { name: "x" }, + "jest.config.json": { + preset: "react-native", + setupFiles: [ + "./node_modules/react-native-gesture-handler/jestSetup.js", + "/node_modules/@shopify/flash-list/jestSetup.js", + ], + }, + "node_modules/react-native-gesture-handler/package.json": { + name: "react-native-gesture-handler", + version: "3.4.0", + }, + "node_modules/@shopify/flash-list/package.json": { + name: "@shopify/flash-list", + version: "2.3.3", + }, + }); + const report = analyzeJestConfig(root); + const covered = report.presetCovered.join("\n"); + expect(covered).toContain( + "'./node_modules/react-native-gesture-handler/jestSetup.js' — react-native-gesture-handler's own test setup, which the native engine runs", + ); + expect(covered).toContain( + "'/node_modules/@shopify/flash-list/jestSetup.js' — @shopify/flash-list's own test setup, which the native engine runs", + ); + expect(report.suggestedConfig).not.toContain("jestSetup"); + }); + + it("keeps a library's other setup file, which the native engine does not run", () => { + const root = fixture({ + "package.json": { name: "x" }, + "jest.config.json": { + preset: "react-native", + setupFiles: ["react-native-gesture-handler/lib/extra-setup.js"], + }, + "node_modules/react-native-gesture-handler/package.json": { + name: "react-native-gesture-handler", + version: "3.4.0", + }, + }); + const report = analyzeJestConfig(root); + expect(report.presetCovered.join("\n")).not.toContain("extra-setup"); + expect(report.suggestedConfig).toContain("extra-setup"); + }); + it("rewrites in setup files instead of emitting it verbatim", () => { // The case above uses "./jest.setup.js", which happens to work as written. Real // Jest configs overwhelmingly say "/jest.setup.js", and Vitest does not diff --git a/packages/vitest-native/tests/preset-engine.test.ts b/packages/vitest-native/tests/preset-engine.test.ts index d29b624a5..028b2675f 100644 --- a/packages/vitest-native/tests/preset-engine.test.ts +++ b/packages/vitest-native/tests/preset-engine.test.ts @@ -12,10 +12,12 @@ import { activePresets } from "../src/cli/manifest.js"; import { autoDetectedPresetApplies, NATIVE_ENGINE_RUNS_PACKAGES } from "../src/preset-map.js"; describe("autoDetectedPresetApplies", () => { - it("steps the expo preset aside under the native engine only", () => { - expect(NATIVE_ENGINE_RUNS_PACKAGES).toEqual(["expo"]); - expect(autoDetectedPresetApplies("expo", "native")).toBe(false); - expect(autoDetectedPresetApplies("expo", "mock")).toBe(true); + it("steps the expo, gesture-handler and flash-list presets aside under the native engine only", () => { + expect(NATIVE_ENGINE_RUNS_PACKAGES).toEqual(["expo", "gestureHandler", "flashList"]); + for (const preset of NATIVE_ENGINE_RUNS_PACKAGES) { + expect(autoDetectedPresetApplies(preset, "native")).toBe(false); + expect(autoDetectedPresetApplies(preset, "mock")).toBe(true); + } // These apply, with the library's own mock as their module there. for (const preset of ["reanimated", "worklets", "safeAreaContext"]) { expect(autoDetectedPresetApplies(preset, "native")).toBe(true); diff --git a/website/guide/presets.md b/website/guide/presets.md index 8a17e7bcd..363223ab7 100644 --- a/website/guide/presets.md +++ b/website/guide/presets.md @@ -41,7 +41,7 @@ Presets apply under **both** engines. |--------|---------|---------------| | `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: 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` | `GestureHandlerRootView`, gesture handlers (Pan, Tap, LongPress, Pinch, Rotation, Fling), `Gesture` API (v2), `GestureDetector`, `Swipeable`, touchable wrappers, state constants | +| `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 `` 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` | @@ -53,7 +53,7 @@ Presets apply under **both** engines. | `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.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 |