vitest-native 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +731 -0
- package/README.md +32 -1
- package/dist/cli.cjs +163 -27
- package/dist/cli.mjs +162 -26
- package/dist/{ecosystem-EFtHnKS9.mjs → ecosystem-CO5vqExO.mjs} +77 -15
- package/dist/{ecosystem-BIWaVwYL.cjs → ecosystem-IuZ-Gv0R.cjs} +78 -16
- package/dist/errors-Dm5yLNTF.mjs +64 -0
- package/dist/errors-flXDIeWk.cjs +75 -0
- package/dist/errors.d.mts +46 -0
- package/dist/errors.mjs +78 -0
- package/dist/helpers.cjs +6 -23
- package/dist/helpers.d.cts +0 -6
- package/dist/helpers.d.mts +0 -6
- package/dist/helpers.mjs +6 -23
- package/dist/{index-CEgRDdhd.d.cts → index-BJL4cQ-l.d.cts} +9 -4
- package/dist/{index-j-0tueBr.d.mts → index-CvCU0cLl.d.mts} +9 -4
- package/dist/index.d.mts +8 -6
- package/dist/index.mjs +245 -59
- package/dist/jest-compat/interop.mjs +15 -0
- package/dist/jest-compat/setup.mjs +102 -7
- package/dist/matchers.cjs +16 -7
- package/dist/matchers.mjs +16 -7
- package/dist/native/hooks.mjs +75 -1
- package/dist/native/loader.mjs +26 -6
- package/dist/native/module-reset.mjs +63 -0
- package/dist/native/registry.mjs +80 -11
- package/dist/native/resolve.d.mts +22 -0
- package/dist/native/resolve.mjs +21 -13
- package/dist/native/runner.mjs +21 -0
- package/dist/native/setup.mjs +4 -2
- package/dist/native/transform.mjs +108 -3
- package/dist/native/worker.mjs +59 -16
- package/dist/{pool-CJmjRgsB.mjs → pool-Bcxp4Qrg.mjs} +2 -1
- package/dist/{pool-DzsEo9vv.cjs → pool-CFND7plG.cjs} +2 -1
- package/dist/{preset-map-CNsZKfvu.mjs → preset-map-BpDG_D5m.mjs} +0 -1
- package/dist/{preset-map-CG4FMtsl.cjs → preset-map-DxilQ4pI.cjs} +0 -1
- package/dist/{presets-C4faM3ds.cjs → presets-BGTqVH6C.cjs} +94 -50
- package/dist/{presets-CuDrNA_W.mjs → presets-CK85x8ey.mjs} +94 -50
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/rntl-matchers.d.ts +35 -0
- package/dist/serializer.cjs +33 -3
- package/dist/serializer.mjs +33 -3
- package/dist/setup.mjs +234 -71
- package/docs/release-readiness.md +22 -5
- package/docs/versioning.md +133 -0
- package/package.json +25 -35
- package/dist/index.cjs +0 -788
- package/dist/index.d.cts +0 -14
- package/dist/presets.cjs +0 -18
- package/dist/presets.d.cts +0 -2
- package/dist/setup.cjs +0 -2702
- package/dist/setup.d.cts +0 -1
package/dist/helpers.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t as VitestNativeError } from "./errors-Dm5yLNTF.mjs";
|
|
1
2
|
//#region src/helpers.ts
|
|
2
3
|
/**
|
|
3
4
|
* Test helpers for vitest-native.
|
|
@@ -7,7 +8,7 @@
|
|
|
7
8
|
*/
|
|
8
9
|
function getMock() {
|
|
9
10
|
const mock = globalThis.__vitest_native_mock;
|
|
10
|
-
if (!mock) throw new
|
|
11
|
+
if (!mock) throw new VitestNativeError("HELPERS_BEFORE_SETUP", "helpers were called before setup ran. Ensure the vitest-native plugin is configured.");
|
|
11
12
|
return mock;
|
|
12
13
|
}
|
|
13
14
|
function getNativeControl() {
|
|
@@ -80,21 +81,10 @@ function resetAllMocks() {
|
|
|
80
81
|
mock.Platform.select.mockImplementation((specifics) => {
|
|
81
82
|
return specifics.ios ?? specifics.default;
|
|
82
83
|
});
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
height: 844,
|
|
88
|
-
scale: 3,
|
|
89
|
-
fontScale: 1
|
|
90
|
-
},
|
|
91
|
-
screen: {
|
|
92
|
-
width: 390,
|
|
93
|
-
height: 844,
|
|
94
|
-
scale: 3,
|
|
95
|
-
fontScale: 1
|
|
96
|
-
}
|
|
97
|
-
});
|
|
84
|
+
for (const value of Object.values(mock)) {
|
|
85
|
+
const candidate = value;
|
|
86
|
+
if (candidate && typeof candidate === "object" && typeof candidate._reset === "function") candidate._reset();
|
|
87
|
+
}
|
|
98
88
|
if (mock.useWindowDimensions._resetDimensions) mock.useWindowDimensions._resetDimensions({
|
|
99
89
|
width: 390,
|
|
100
90
|
height: 844,
|
|
@@ -107,15 +97,8 @@ function resetAllMocks() {
|
|
|
107
97
|
scale: 3,
|
|
108
98
|
fontScale: 1
|
|
109
99
|
});
|
|
110
|
-
if (mock.Appearance._reset) mock.Appearance._reset();
|
|
111
|
-
else mock.Appearance.setColorScheme("light");
|
|
112
100
|
if (mock.useColorScheme._resetScheme) mock.useColorScheme._resetScheme("light");
|
|
113
101
|
else if (mock.useColorScheme._setScheme) mock.useColorScheme._setScheme("light");
|
|
114
|
-
if (mock.Keyboard._reset) mock.Keyboard._reset();
|
|
115
|
-
if (mock.AppState._reset) mock.AppState._reset();
|
|
116
|
-
if (mock.BackHandler._reset) mock.BackHandler._reset();
|
|
117
|
-
if (mock.I18nManager._reset) mock.I18nManager._reset();
|
|
118
|
-
if (mock.DeviceEventEmitter._reset) mock.DeviceEventEmitter._reset();
|
|
119
102
|
if (originalNativeModules !== null) {
|
|
120
103
|
mock.NativeModules = originalNativeModules;
|
|
121
104
|
originalNativeModules = null;
|
|
@@ -244,9 +244,14 @@ interface VitestNativeOptions {
|
|
|
244
244
|
*/
|
|
245
245
|
engine?: "auto" | "mock" | "native";
|
|
246
246
|
/**
|
|
247
|
-
* Built-in third-party library presets.
|
|
248
|
-
*
|
|
249
|
-
*
|
|
247
|
+
* Built-in third-party library presets.
|
|
248
|
+
*
|
|
249
|
+
* An ARRAY replaces auto-detection entirely: only those presets are used.
|
|
250
|
+
*
|
|
251
|
+
* An OBJECT keeps auto-detection and turns individual presets off by name —
|
|
252
|
+
* `{ navigation: false }` — which is what you want when one preset gets in the
|
|
253
|
+
* way. Listing every other detected preset back by hand just to drop one is
|
|
254
|
+
* both tedious and a thing that silently rots as dependencies change.
|
|
250
255
|
*
|
|
251
256
|
* Only built-in presets are supported (reanimated, gestureHandler,
|
|
252
257
|
* safeAreaContext, navigation, asyncStorage, screens, expo). For custom
|
|
@@ -258,7 +263,7 @@ interface VitestNativeOptions {
|
|
|
258
263
|
* reactNative({ presets: [presets.reanimated(), presets.navigation()] })
|
|
259
264
|
* ```
|
|
260
265
|
*/
|
|
261
|
-
presets?: Preset[]
|
|
266
|
+
presets?: Preset[] | Record<string, boolean>;
|
|
262
267
|
/**
|
|
263
268
|
* `engine: 'mock'` only. Plain-data overrides merged into the react-native
|
|
264
269
|
* module mock.
|
|
@@ -242,9 +242,14 @@ interface VitestNativeOptions {
|
|
|
242
242
|
*/
|
|
243
243
|
engine?: "auto" | "mock" | "native";
|
|
244
244
|
/**
|
|
245
|
-
* Built-in third-party library presets.
|
|
246
|
-
*
|
|
247
|
-
*
|
|
245
|
+
* Built-in third-party library presets.
|
|
246
|
+
*
|
|
247
|
+
* An ARRAY replaces auto-detection entirely: only those presets are used.
|
|
248
|
+
*
|
|
249
|
+
* An OBJECT keeps auto-detection and turns individual presets off by name —
|
|
250
|
+
* `{ navigation: false }` — which is what you want when one preset gets in the
|
|
251
|
+
* way. Listing every other detected preset back by hand just to drop one is
|
|
252
|
+
* both tedious and a thing that silently rots as dependencies change.
|
|
248
253
|
*
|
|
249
254
|
* Only built-in presets are supported (reanimated, gestureHandler,
|
|
250
255
|
* safeAreaContext, navigation, asyncStorage, screens, expo). For custom
|
|
@@ -256,7 +261,7 @@ interface VitestNativeOptions {
|
|
|
256
261
|
* reactNative({ presets: [presets.reanimated(), presets.navigation()] })
|
|
257
262
|
* ```
|
|
258
263
|
*/
|
|
259
|
-
presets?: Preset[]
|
|
264
|
+
presets?: Preset[] | Record<string, boolean>;
|
|
260
265
|
/**
|
|
261
266
|
* `engine: 'mock'` only. Plain-data overrides merged into the react-native
|
|
262
267
|
* module mock.
|
package/dist/index.d.mts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
import { b as VitestNativeOptions, t as index_d_exports, v as Preset, y as ReactNativeMock } from "./index-
|
|
1
|
+
import { b as VitestNativeOptions, t as index_d_exports, v as Preset, y as ReactNativeMock } from "./index-CvCU0cLl.mjs";
|
|
2
2
|
import { Plugin } from "vite";
|
|
3
3
|
|
|
4
4
|
//#region src/plugin.d.ts
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
6
|
+
* Preset names switched off by the object form of the `presets` option.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* The array form replaces auto-detection wholesale, which meant that turning ONE
|
|
9
|
+
* preset off required listing every other detected preset by hand — tedious, and a
|
|
10
|
+
* list that silently rots as dependencies change. The object form keeps detection
|
|
11
|
+
* and names only what to drop.
|
|
11
12
|
*/
|
|
13
|
+
declare function disabledPresetNames(presets: unknown): Set<string>;
|
|
12
14
|
declare function reactNative(options?: VitestNativeOptions): Plugin;
|
|
13
15
|
//#endregion
|
|
14
|
-
export { type Preset, type ReactNativeMock, type VitestNativeOptions, index_d_exports as presets, reactNative };
|
|
16
|
+
export { type Preset, type ReactNativeMock, type VitestNativeOptions, disabledPresetNames, index_d_exports as presets, reactNative };
|
package/dist/index.mjs
CHANGED
|
@@ -1,40 +1,54 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as
|
|
3
|
-
import { t as
|
|
1
|
+
import { t as VitestNativeError } from "./errors-Dm5yLNTF.mjs";
|
|
2
|
+
import { a as validatePeerDependency, i as validateOptions, n as detectEngine, o as warnUnknownOptions, r as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-CO5vqExO.mjs";
|
|
3
|
+
import { t as AUTO_DETECT_PRESETS } from "./preset-map-BpDG_D5m.mjs";
|
|
4
|
+
import { t as presets_exports } from "./presets-CK85x8ey.mjs";
|
|
4
5
|
import { createRequire } from "node:module";
|
|
5
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
-
import path from "node:path";
|
|
7
6
|
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
9
|
import flowRemoveTypes from "flow-remove-types";
|
|
9
|
-
//#region src/resolve.
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
"
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
".android.jsx",
|
|
28
|
-
".android.js",
|
|
29
|
-
".native.tsx",
|
|
30
|
-
".native.ts",
|
|
31
|
-
".native.jsx",
|
|
32
|
-
".native.js",
|
|
33
|
-
".tsx",
|
|
34
|
-
".ts",
|
|
35
|
-
".jsx",
|
|
36
|
-
".js"
|
|
10
|
+
//#region src/native/resolve.mjs
|
|
11
|
+
/**
|
|
12
|
+
* Metro's default `sourceExts`, in its order. Kept as data rather than spelled out
|
|
13
|
+
* per platform so the Vite graph and the Node graph cannot drift apart — both build
|
|
14
|
+
* their list from this one array (see `getPlatformExtensions` in ../resolve.ts).
|
|
15
|
+
*
|
|
16
|
+
* The order is load-bearing where a module has more than one variant on disk:
|
|
17
|
+
* Metro picks `Foo.js` over `Foo.tsx`, so this list must too, or a project with a
|
|
18
|
+
* compiled file beside its source tests a different file than it ships. `json` is
|
|
19
|
+
* a source extension to Metro, which is why `import config from './config'`
|
|
20
|
+
* resolves `config.json` in an app.
|
|
21
|
+
*/
|
|
22
|
+
const METRO_SOURCE_EXTS = [
|
|
23
|
+
"js",
|
|
24
|
+
"jsx",
|
|
25
|
+
"json",
|
|
26
|
+
"ts",
|
|
27
|
+
"tsx"
|
|
37
28
|
];
|
|
29
|
+
/**
|
|
30
|
+
* Metro tries every platform-suffixed variant first, then every `.native` one,
|
|
31
|
+
* then the bare extensions — not extension-major.
|
|
32
|
+
*/
|
|
33
|
+
function extensionsFor(platform) {
|
|
34
|
+
const suffix = platform === "android" ? "android" : "ios";
|
|
35
|
+
return [
|
|
36
|
+
...METRO_SOURCE_EXTS.map((e) => `.${suffix}.${e}`),
|
|
37
|
+
...METRO_SOURCE_EXTS.map((e) => `.native.${e}`),
|
|
38
|
+
...METRO_SOURCE_EXTS.map((e) => `.${e}`)
|
|
39
|
+
];
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/resolve.ts
|
|
43
|
+
/**
|
|
44
|
+
* Extension search order for the Vite graph, taken from the same definition the
|
|
45
|
+
* Node graph uses. Vite's default list is replaced wholesale by whatever is set
|
|
46
|
+
* here, so anything Metro treats as a source extension has to appear — `.json`
|
|
47
|
+
* included, or `import config from './config'` resolves in the app and fails in
|
|
48
|
+
* the test.
|
|
49
|
+
*/
|
|
50
|
+
const PLATFORM_EXTENSIONS_IOS = extensionsFor("ios");
|
|
51
|
+
const PLATFORM_EXTENSIONS_ANDROID = extensionsFor("android");
|
|
38
52
|
function getPlatformExtensions(platform) {
|
|
39
53
|
return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
|
|
40
54
|
}
|
|
@@ -69,14 +83,15 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
|
|
|
69
83
|
if (dir) patterns.push(new RegExp(`^${escapeRe(dir.replace(/\\/g, "/"))}[\\\\/]`));
|
|
70
84
|
return patterns;
|
|
71
85
|
});
|
|
72
|
-
const
|
|
86
|
+
const ecosystemExternal = inlinePkgs.flatMap((p) => {
|
|
73
87
|
const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`)];
|
|
74
88
|
const dir = resolvePackageDir(p, projectRoot);
|
|
75
89
|
if (dir) patterns.push(new RegExp(`^${escapeRe(dir.replace(/\\/g, "/"))}[\\\\/]`));
|
|
76
90
|
return patterns;
|
|
77
91
|
});
|
|
92
|
+
const nodeTransformed = [...new Set([...transformPkgs, ...inlinePkgs])];
|
|
78
93
|
const fullEnv = { ...env };
|
|
79
|
-
if (
|
|
94
|
+
if (nodeTransformed.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(nodeTransformed);
|
|
80
95
|
return {
|
|
81
96
|
...jsxTransform,
|
|
82
97
|
ssr: { resolve: {
|
|
@@ -112,14 +127,12 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
|
|
|
112
127
|
isolate: false,
|
|
113
128
|
runner: hot.runnerPath
|
|
114
129
|
} : { pool: userPool ?? "threads" },
|
|
115
|
-
server: { deps: {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
...ecosystemInline.length > 0 ? { inline: ecosystemInline } : {}
|
|
122
|
-
} }
|
|
130
|
+
server: { deps: { external: [
|
|
131
|
+
/[\\/]node_modules[\\/]react-native[\\/]/,
|
|
132
|
+
/[\\/]node_modules[\\/]@react-native[\\/]/,
|
|
133
|
+
...extraExternal,
|
|
134
|
+
...ecosystemExternal
|
|
135
|
+
] } }
|
|
123
136
|
}
|
|
124
137
|
};
|
|
125
138
|
}
|
|
@@ -301,8 +314,12 @@ async function resolveOptions(options = {}, projectRoot) {
|
|
|
301
314
|
const engine = options.engine === "native" ? "native" : "mock";
|
|
302
315
|
const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
|
|
303
316
|
let presets;
|
|
304
|
-
if (options.presets) presets = options.presets;
|
|
305
|
-
else
|
|
317
|
+
if (Array.isArray(options.presets)) presets = options.presets;
|
|
318
|
+
else {
|
|
319
|
+
const detected = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
|
|
320
|
+
const disabled = disabledPresetNames(options.presets);
|
|
321
|
+
presets = disabled.size > 0 ? detected.filter((p) => !disabled.has(p.name)) : detected;
|
|
322
|
+
}
|
|
306
323
|
return {
|
|
307
324
|
platform,
|
|
308
325
|
engine,
|
|
@@ -413,6 +430,34 @@ const RN_EXPORT_NAMES = [
|
|
|
413
430
|
* it replaced: `eslint-plugin-react-native` and a project directory called
|
|
414
431
|
* `react-native-app` both contain the words without being React Native packages.
|
|
415
432
|
*/
|
|
433
|
+
/**
|
|
434
|
+
* Two copies of React in one test process produce a null hooks dispatcher, which
|
|
435
|
+
* surfaces as `Cannot read properties of null (reading 'use')` — usually wrapped by
|
|
436
|
+
* React Native Testing Library as "Trying to detect host component names triggered the
|
|
437
|
+
* following error", whose own advice is only that something is wrong with the
|
|
438
|
+
* configuration. `resolve.dedupe` prevents it in the normal case; this reports the
|
|
439
|
+
* cases dedupe cannot reach, such as a nested install, so the cause is named rather
|
|
440
|
+
* than discovered.
|
|
441
|
+
*
|
|
442
|
+
* Pure and exported for testing: `resolve` is the resolver, so the check can be
|
|
443
|
+
* exercised without building a broken node_modules tree.
|
|
444
|
+
*/
|
|
445
|
+
function findDuplicateReact(resolve, projectRoot, consumers) {
|
|
446
|
+
const projectCopy = resolve("react/package.json", projectRoot);
|
|
447
|
+
if (!projectCopy) return null;
|
|
448
|
+
for (const consumer of consumers) {
|
|
449
|
+
const consumerRoot = resolve(`${consumer}/package.json`, projectRoot);
|
|
450
|
+
if (!consumerRoot) continue;
|
|
451
|
+
const otherCopy = resolve("react/package.json", consumerRoot);
|
|
452
|
+
if (otherCopy && otherCopy !== projectCopy) return {
|
|
453
|
+
projectCopy,
|
|
454
|
+
otherCopy,
|
|
455
|
+
consumer
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
const HAS_JEST_MOCK_CALL = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
|
|
416
461
|
const RN_ECOSYSTEM_PATH = /[\\/]node_modules[\\/](?:@react-native[^\\/]*[\\/][^\\/]+|(?:@[^\\/]+[\\/])?react-native[^\\/]*)[\\/]/;
|
|
417
462
|
/** Fast membership check for leaf-name lookups on subpath imports. */
|
|
418
463
|
const RN_EXPORT_NAME_SET = new Set(RN_EXPORT_NAMES);
|
|
@@ -468,12 +513,91 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
|
|
|
468
513
|
* modules, and automatic setup-file injection so tests can run against
|
|
469
514
|
* React Native code in a Node/JSDOM environment.
|
|
470
515
|
*/
|
|
516
|
+
/**
|
|
517
|
+
* Fields that select a different FORMAT of the same code — an ESM build beside a CJS
|
|
518
|
+
* one. Vite prefers them, Node reads `main`, and the two builds are interchangeable,
|
|
519
|
+
* so pointing Vite at `main` costs nothing and collapses the pair into one instance.
|
|
520
|
+
*
|
|
521
|
+
* `react-native` is deliberately NOT here. That field selects a different
|
|
522
|
+
* IMPLEMENTATION — the native build rather than the web one — and Metro resolves it
|
|
523
|
+
* ahead of `main`, so the engine must too (see tests-native/export-conditions.test.ts).
|
|
524
|
+
* Aligning it downward would quietly load the web build, which is a fidelity
|
|
525
|
+
* regression, not a deduplication. Packages using it stay split and are reported by
|
|
526
|
+
* the duplicate-instance warning instead; fixing those means teaching Node to load
|
|
527
|
+
* the native build, which needs the transform pipeline and is a separate change.
|
|
528
|
+
*/
|
|
529
|
+
const FORMAT_ONLY_FIELDS = [
|
|
530
|
+
"module",
|
|
531
|
+
"jsnext:main",
|
|
532
|
+
"jsnext"
|
|
533
|
+
];
|
|
534
|
+
/**
|
|
535
|
+
* Make Vite resolve a package to the same file Node will.
|
|
536
|
+
*
|
|
537
|
+
* The native engine runs two module systems. Vitest already forwards
|
|
538
|
+
* `resolve.conditions` to the worker's Node (`--conditions react-native ...`), so a
|
|
539
|
+
* package using an `exports` map resolves identically on both sides. Legacy
|
|
540
|
+
* top-level fields have no such bridge: Vite reads `react-native`/`module`, Node
|
|
541
|
+
* reads `main`, and a package publishing both ends up loaded twice with separate
|
|
542
|
+
* module-level state. A store written through one copy reads back unset through the
|
|
543
|
+
* other — silently, since nothing fails.
|
|
544
|
+
*
|
|
545
|
+
* Aligning downward, onto the file Node picks, is the direction that cannot break a
|
|
546
|
+
* working suite: the `main` build is by definition something Node can execute,
|
|
547
|
+
* whereas the `react-native` field usually points at untranspiled source that Node
|
|
548
|
+
* cannot parse at all. Aligning upward would turn a wrong-value bug into a crash for
|
|
549
|
+
* any package the engine does not also transform.
|
|
550
|
+
*
|
|
551
|
+
* Packages the engine inlines and transforms are left alone: Vite is meant to own
|
|
552
|
+
* their source, and rewriting them to `main` would undo the reason they are inlined.
|
|
553
|
+
*
|
|
554
|
+
* @returns the absolute file to use, or null to leave resolution alone
|
|
555
|
+
*/
|
|
556
|
+
function alignLegacyFieldsWithNode(source, packageDirFor, readManifest, resolveAsNodeWould, isEngineOwned) {
|
|
557
|
+
if (!source || source.startsWith(".") || source.startsWith("/") || source.startsWith("\0")) return null;
|
|
558
|
+
const segments = source.split("/");
|
|
559
|
+
const name = source.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
|
|
560
|
+
if (!name || segments.length > (source.startsWith("@") ? 2 : 1)) return null;
|
|
561
|
+
if (isEngineOwned(name)) return null;
|
|
562
|
+
const dir = packageDirFor(name);
|
|
563
|
+
if (!dir) return null;
|
|
564
|
+
const manifest = readManifest(dir);
|
|
565
|
+
if (!manifest) return null;
|
|
566
|
+
if (manifest.exports !== void 0) return null;
|
|
567
|
+
if (typeof manifest["react-native"] === "string") return null;
|
|
568
|
+
const legacy = FORMAT_ONLY_FIELDS.map((f) => manifest[f]).find((v) => typeof v === "string");
|
|
569
|
+
if (typeof legacy !== "string") return null;
|
|
570
|
+
const nodeFile = resolveAsNodeWould(name);
|
|
571
|
+
if (!nodeFile) return null;
|
|
572
|
+
if (path.resolve(dir, legacy) === nodeFile) return null;
|
|
573
|
+
return nodeFile;
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Preset names switched off by the object form of the `presets` option.
|
|
577
|
+
*
|
|
578
|
+
* The array form replaces auto-detection wholesale, which meant that turning ONE
|
|
579
|
+
* preset off required listing every other detected preset by hand — tedious, and a
|
|
580
|
+
* list that silently rots as dependencies change. The object form keeps detection
|
|
581
|
+
* and names only what to drop.
|
|
582
|
+
*/
|
|
583
|
+
function disabledPresetNames(presets) {
|
|
584
|
+
if (!presets || Array.isArray(presets) || typeof presets !== "object") return /* @__PURE__ */ new Set();
|
|
585
|
+
return new Set(Object.entries(presets).filter(([, enabled]) => enabled === false).map(([name]) => name));
|
|
586
|
+
}
|
|
471
587
|
function reactNative(options) {
|
|
588
|
+
let jestMockTransformPresent = true;
|
|
589
|
+
let warnedMissingJestMockTransform = false;
|
|
590
|
+
const warnIfJestMockUnhoisted = (code, id) => {
|
|
591
|
+
if (jestMockTransformPresent || warnedMissingJestMockTransform) return;
|
|
592
|
+
if (!HAS_JEST_MOCK_CALL.test(code)) return;
|
|
593
|
+
warnedMissingJestMockTransform = true;
|
|
594
|
+
console.warn(`[vitest-native] ${id} calls jest.mock(), but jestMockTransform() is not in your plugins. Vitest only hoists mocks written on the vi/vitest identifier, so this call runs after the imports it should intercept and the mock will not apply.\nAdd it AFTER reactNative():\n\n import { jestMockTransform } from 'vitest-native/jest-compat'\n plugins: [reactNative(), jestMockTransform()]`);
|
|
595
|
+
};
|
|
472
596
|
if (options) {
|
|
473
597
|
validateOptions(options);
|
|
474
598
|
warnUnknownOptions(options);
|
|
475
599
|
}
|
|
476
|
-
if (options?.mocks && containsFunctions(options.mocks)) throw new
|
|
600
|
+
if (options?.mocks && containsFunctions(options.mocks)) throw new VitestNativeError("INVALID_OPTION", "The \"mocks\" option contains function values, which cannot be transferred to Vitest worker processes. Only JSON-serializable values (strings, numbers, booleans, plain objects, arrays) are supported.\n\nFor function-based mock overrides, use vi.mock() in a setup file:\n\n // vitest.setup.ts\n import { vi } from 'vitest';\n vi.mock('react-native', async (importOriginal) => {\n const actual = await importOriginal();\n return { ...actual, Alert: { alert: vi.fn() } };\n });");
|
|
477
601
|
let resolved;
|
|
478
602
|
const presetModules = /* @__PURE__ */ new Map();
|
|
479
603
|
const presetExportNames = /* @__PURE__ */ new Map();
|
|
@@ -482,7 +606,43 @@ function reactNative(options) {
|
|
|
482
606
|
let rnFacadeExports = null;
|
|
483
607
|
let rnFacadeRoot = "";
|
|
484
608
|
let ecosystemPattern = null;
|
|
609
|
+
let alignRoot = "";
|
|
485
610
|
let ecosystemRoot = "";
|
|
611
|
+
const alignedCache = /* @__PURE__ */ new Map();
|
|
612
|
+
const alignedResolution = (source, importer) => {
|
|
613
|
+
if (engine !== "native") return void 0;
|
|
614
|
+
const from = importer && path.isAbsolute(importer) && !importer.startsWith("\0") ? importer : path.join(alignRoot || process.cwd(), "package.json");
|
|
615
|
+
const key = `${from}\u0000${source}`;
|
|
616
|
+
const cached = alignedCache.get(key);
|
|
617
|
+
if (cached !== void 0) return cached ?? void 0;
|
|
618
|
+
let result = null;
|
|
619
|
+
try {
|
|
620
|
+
const req = createRequire(from);
|
|
621
|
+
result = alignLegacyFieldsWithNode(source, (name) => {
|
|
622
|
+
try {
|
|
623
|
+
return path.dirname(req.resolve(`${name}/package.json`));
|
|
624
|
+
} catch {
|
|
625
|
+
return null;
|
|
626
|
+
}
|
|
627
|
+
}, (dir) => {
|
|
628
|
+
try {
|
|
629
|
+
return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
|
|
630
|
+
} catch {
|
|
631
|
+
return null;
|
|
632
|
+
}
|
|
633
|
+
}, (name) => {
|
|
634
|
+
try {
|
|
635
|
+
return req.resolve(name);
|
|
636
|
+
} catch {
|
|
637
|
+
return null;
|
|
638
|
+
}
|
|
639
|
+
}, (name) => name === "react-native" || name.startsWith("@react-native"));
|
|
640
|
+
} catch {
|
|
641
|
+
result = null;
|
|
642
|
+
}
|
|
643
|
+
alignedCache.set(key, result);
|
|
644
|
+
return result ?? void 0;
|
|
645
|
+
};
|
|
486
646
|
const resolveCache = /* @__PURE__ */ new Map();
|
|
487
647
|
const virtualCodeCache = /* @__PURE__ */ new Map();
|
|
488
648
|
const thisDir = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -515,10 +675,11 @@ function reactNative(options) {
|
|
|
515
675
|
enforce: "pre",
|
|
516
676
|
async config(userConfig, _env) {
|
|
517
677
|
const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
|
|
678
|
+
alignRoot = resolvedRoot;
|
|
518
679
|
const jsxTransform = getJsxTransformConfig(resolvedRoot);
|
|
519
680
|
const decision = detectEngine(requestedEngine, resolvedRoot);
|
|
520
681
|
engine = decision.engine;
|
|
521
|
-
if (engine === "native" && !decision.nativeAvailable) throw new
|
|
682
|
+
if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires '@react-native/babel-preset' and '@babel/core' to resolve from ${resolvedRoot}. Install them as devDependencies (React Native projects ship them by default):\n\n npm install -D @react-native/babel-preset @babel/core\n\nOr set engine:'mock' to run without a React Native install.`);
|
|
522
683
|
if (decision.notice) console.warn(decision.notice);
|
|
523
684
|
printEngineBanner(engine, platform, resolvedRoot);
|
|
524
685
|
const env = {
|
|
@@ -532,10 +693,11 @@ function reactNative(options) {
|
|
|
532
693
|
env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
|
|
533
694
|
if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
|
|
534
695
|
if (engine === "native") {
|
|
535
|
-
if (options?.mocks && Object.keys(options.mocks).length > 0) throw new
|
|
536
|
-
const
|
|
696
|
+
if (options?.mocks && Object.keys(options.mocks).length > 0) throw new VitestNativeError("MOCKS_REQUIRE_MOCK_ENGINE", "The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
|
|
697
|
+
const disabledNative = disabledPresetNames(options?.presets);
|
|
698
|
+
const nativePresetNames = Array.isArray(options?.presets) ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics).filter((n) => !disabledNative.has(n));
|
|
537
699
|
if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
|
|
538
|
-
if (options?.presets) {
|
|
700
|
+
if (Array.isArray(options?.presets)) {
|
|
539
701
|
const presetConfig = {};
|
|
540
702
|
for (const p of options.presets) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
|
|
541
703
|
if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
|
|
@@ -556,7 +718,7 @@ function reactNative(options) {
|
|
|
556
718
|
if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
|
|
557
719
|
let hot;
|
|
558
720
|
if (hotRuntime) {
|
|
559
|
-
const { nativePool, defaultHotMemoryLimit } = await import("./pool-
|
|
721
|
+
const { nativePool, defaultHotMemoryLimit } = await import("./pool-Bcxp4Qrg.mjs");
|
|
560
722
|
const memoryLimit = hotRecycle.memoryLimit ?? (hotRecycle.recycleAfterFiles == null ? defaultHotMemoryLimit() : void 0);
|
|
561
723
|
hot = {
|
|
562
724
|
pool: nativePool({
|
|
@@ -570,13 +732,17 @@ function reactNative(options) {
|
|
|
570
732
|
};
|
|
571
733
|
}
|
|
572
734
|
const userPool = userConfig.test?.pool;
|
|
573
|
-
if (userPool === "vmThreads" || userPool === "vmForks") throw new
|
|
735
|
+
if (userPool === "vmThreads" || userPool === "vmForks") throw new VitestNativeError("UNSUPPORTED_POOL", `engine:'native' cannot run on the '${userPool}' pool. React Native is loaded through Node's module hooks, which a VM pool's context does not use — React Native fails to resolve its platform files there. Use 'threads' (the default) or 'forks', or switch to engine:'mock', which needs no hooks.`);
|
|
574
736
|
if (hot && userPool) console.warn(`[vitest-native] 'hotRuntime' supplies its own pool, overriding the configured pool '${typeof userPool === "string" ? userPool : "(custom)"}'.`);
|
|
575
737
|
return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot));
|
|
576
738
|
}
|
|
577
739
|
if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
|
|
578
740
|
if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
|
|
579
|
-
if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
|
|
741
|
+
if (Array.isArray(options?.presets)) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
|
|
742
|
+
else {
|
|
743
|
+
const disabled = disabledPresetNames(options?.presets);
|
|
744
|
+
if (disabled.size > 0) env.VITEST_NATIVE_PRESET_DISABLED = JSON.stringify([...disabled]);
|
|
745
|
+
}
|
|
580
746
|
return asCompatibleViteConfig({
|
|
581
747
|
...jsxTransform,
|
|
582
748
|
ssr: { resolve: {
|
|
@@ -611,14 +777,31 @@ function reactNative(options) {
|
|
|
611
777
|
});
|
|
612
778
|
},
|
|
613
779
|
async configResolved(config) {
|
|
780
|
+
jestMockTransformPresent = (config.plugins ?? []).some((plugin) => plugin?.name === "vitest-native:jest-mock-hoist");
|
|
781
|
+
const duplicateReact = findDuplicateReact((specifier, from) => {
|
|
782
|
+
try {
|
|
783
|
+
return createRequire(path.join(from, "package.json")).resolve(specifier);
|
|
784
|
+
} catch {
|
|
785
|
+
return null;
|
|
786
|
+
}
|
|
787
|
+
}, config.root, [
|
|
788
|
+
"@testing-library/react-native",
|
|
789
|
+
"react-test-renderer",
|
|
790
|
+
"react-native"
|
|
791
|
+
]);
|
|
792
|
+
if (duplicateReact) console.warn(`[vitest-native] Two copies of React are resolvable: your project loads one, and '${duplicateReact.consumer}' loads another.\n project: ${duplicateReact.projectCopy}\n ${duplicateReact.consumer}: ${duplicateReact.otherCopy}\nReact throws "Cannot read properties of null (reading 'use')" when hooks run through a second copy, which React Native Testing Library reports as a failure to detect host component names. Install a single React version at the project root (npm dedupe, or match the version '${duplicateReact.consumer}' expects).`);
|
|
614
793
|
const peerErrors = [];
|
|
615
|
-
for (const { name, minimum, maximumMajor, minimumByMajor } of PEER_REQUIREMENTS) {
|
|
794
|
+
for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
|
|
795
|
+
if (optional) continue;
|
|
616
796
|
const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
|
|
617
797
|
if (error) peerErrors.push(error);
|
|
618
798
|
}
|
|
619
|
-
if (peerErrors.length > 0) throw new
|
|
620
|
-
const
|
|
621
|
-
|
|
799
|
+
if (peerErrors.length > 0) throw new VitestNativeError("UNSUPPORTED_PEER", `Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
|
|
800
|
+
for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
|
|
801
|
+
if (!optional) continue;
|
|
802
|
+
const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
|
|
803
|
+
if (error && !error.includes("not found")) console.warn(`[vitest-native] ${error}`);
|
|
804
|
+
}
|
|
622
805
|
resolved = await resolveOptions(options, config.root);
|
|
623
806
|
try {
|
|
624
807
|
realRnPackageJson = createRequire(path.join(config.root, "package.json")).resolve("react-native/package.json");
|
|
@@ -644,7 +827,9 @@ function reactNative(options) {
|
|
|
644
827
|
resolveId(source, importer) {
|
|
645
828
|
if (engine === "native") {
|
|
646
829
|
if (source === "react-native" && rnFacadeExports !== null) return "\0virtual:rn-facade";
|
|
647
|
-
|
|
830
|
+
const presetHit = resolvePresetId(source);
|
|
831
|
+
if (presetHit) return presetHit;
|
|
832
|
+
return alignedResolution(source, importer);
|
|
648
833
|
}
|
|
649
834
|
if (source === "react-native") return "\0virtual:react-native";
|
|
650
835
|
if (source.startsWith("react-native/")) {
|
|
@@ -745,6 +930,7 @@ function reactNative(options) {
|
|
|
745
930
|
}
|
|
746
931
|
},
|
|
747
932
|
transform(code, id) {
|
|
933
|
+
warnIfJestMockUnhoisted(code, id);
|
|
748
934
|
if (engine === "native") {
|
|
749
935
|
if (!ecosystemPattern || !ecosystemPattern.test(id)) return void 0;
|
|
750
936
|
if (!/\.[cm]?[jt]sx?$/.test(id.split("?")[0])) return void 0;
|
|
@@ -774,4 +960,4 @@ function reactNative(options) {
|
|
|
774
960
|
};
|
|
775
961
|
}
|
|
776
962
|
//#endregion
|
|
777
|
-
export { presets_exports as presets, reactNative };
|
|
963
|
+
export { disabledPresetNames, presets_exports as presets, reactNative };
|
|
@@ -16,6 +16,21 @@
|
|
|
16
16
|
// returns (those with `__esModule` or an explicit `default`) untouched.
|
|
17
17
|
export function jestMockInterop(mod) {
|
|
18
18
|
if (mod == null) return mod;
|
|
19
|
+
// An async factory — or any factory returning a promise — resolves to the module
|
|
20
|
+
// shape, so interop applies to the resolved value. Vitest awaits a factory result,
|
|
21
|
+
// so handing the promise back is enough. Without this the promise itself fell into
|
|
22
|
+
// the object branch below, where it has no own enumerable keys and no `default`,
|
|
23
|
+
// producing `{ default: Promise }`: every named export vanished and Vitest reported
|
|
24
|
+
// `No "x" export is defined on the mock` about a vi.mock the author never wrote.
|
|
25
|
+
//
|
|
26
|
+
// Tested by tag rather than by a `then` method: a module may legitimately export a
|
|
27
|
+
// function named `then`, and awaiting that calls it with (resolve, reject) and never
|
|
28
|
+
// settles — a hung test file, which is worse than the bug this fixes. The tag holds
|
|
29
|
+
// for native promises from any realm, and `async` functions and `Promise.resolve`
|
|
30
|
+
// only ever produce those.
|
|
31
|
+
if (Object.prototype.toString.call(mod) === "[object Promise]") {
|
|
32
|
+
return mod.then(jestMockInterop);
|
|
33
|
+
}
|
|
19
34
|
const t = typeof mod;
|
|
20
35
|
if (t === "object" || t === "function") {
|
|
21
36
|
// Already ES-shaped — respect the author's/real module's default export.
|