vitest-native 0.11.1 → 0.13.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 +239 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{ecosystem-DGlajfDG.cjs → ecosystem-CEIF_-jq.cjs} +51 -14
- package/dist/{ecosystem-DJMGR2YY.mjs → ecosystem-Duw40-mO.mjs} +51 -14
- package/dist/helpers.cjs +45 -0
- package/dist/helpers.d.cts +8 -1
- package/dist/helpers.d.mts +8 -1
- package/dist/helpers.mjs +45 -1
- package/dist/{index-DIMbjH8R.d.cts → index-CPGq6p95.d.cts} +36 -1
- package/dist/{index-CrMeE8rd.d.mts → index-CmETArCM.d.mts} +36 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +50 -12
- package/dist/native/explain.mjs +28 -7
- package/dist/native/globals.mjs +22 -3
- package/dist/native/hooks.mjs +43 -8
- package/dist/native/loader.mjs +81 -2
- package/dist/native/module-reset.mjs +10 -5
- package/dist/native/registry.mjs +14 -2
- package/dist/native/resolve.mjs +60 -7
- package/dist/native/setup.mjs +38 -3
- package/dist/native/transform.mjs +149 -37
- package/dist/native/worker.mjs +5 -0
- package/dist/{presets-CwO_c4aL.cjs → presets-CoNf4ByH.cjs} +8 -2
- package/dist/{presets-IStcJEOa.mjs → presets-DGProTaA.mjs} +8 -2
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/setup.mjs +26 -2
- package/docs/migrating-from-vitest-react-native.md +1 -1
- package/docs/versioning.md +1 -1
- package/package.json +4 -3
package/dist/helpers.mjs
CHANGED
|
@@ -48,6 +48,49 @@ function setInsets(insets) {
|
|
|
48
48
|
const safeArea = globalThis.__vitest_native_preset_mocks?.["react-native-safe-area-context"];
|
|
49
49
|
if (safeArea?._setInsets) safeArea._setInsets(insets);
|
|
50
50
|
}
|
|
51
|
+
let presetMockOverrides = [];
|
|
52
|
+
/**
|
|
53
|
+
* Merge overrides into a preset's module mock (and its `default`, when that is
|
|
54
|
+
* an object) — e.g. to give expo-constants a real `expoConfig` or add an export
|
|
55
|
+
* a library calls that the preset does not model. Returns `false` when no
|
|
56
|
+
* preset mock exists for the package. Undone by `resetAllMocks()`.
|
|
57
|
+
*/
|
|
58
|
+
function extendPresetMock(pkg, overrides) {
|
|
59
|
+
const mock = globalThis.__vitest_native_preset_mocks?.[pkg];
|
|
60
|
+
if (!mock) return false;
|
|
61
|
+
const targets = [mock];
|
|
62
|
+
if (mock.default && typeof mock.default === "object" && mock.default !== mock) targets.push(mock.default);
|
|
63
|
+
for (const target of targets) for (const [key, value] of Object.entries(overrides)) {
|
|
64
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
|
|
65
|
+
presetMockOverrides.push({
|
|
66
|
+
target,
|
|
67
|
+
key,
|
|
68
|
+
had: Object.prototype.hasOwnProperty.call(target, key),
|
|
69
|
+
previous: target[key]
|
|
70
|
+
});
|
|
71
|
+
Object.defineProperty(target, key, {
|
|
72
|
+
configurable: true,
|
|
73
|
+
enumerable: true,
|
|
74
|
+
writable: true,
|
|
75
|
+
value
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
function restorePresetMockOverrides() {
|
|
81
|
+
for (let i = presetMockOverrides.length - 1; i >= 0; i--) {
|
|
82
|
+
const { target, key, had, previous } = presetMockOverrides[i];
|
|
83
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
|
|
84
|
+
if (had) Object.defineProperty(target, key, {
|
|
85
|
+
configurable: true,
|
|
86
|
+
enumerable: true,
|
|
87
|
+
writable: true,
|
|
88
|
+
value: previous
|
|
89
|
+
});
|
|
90
|
+
else delete target[key];
|
|
91
|
+
}
|
|
92
|
+
presetMockOverrides = [];
|
|
93
|
+
}
|
|
51
94
|
function mockNativeModule(name, impl) {
|
|
52
95
|
const native = getNativeControl();
|
|
53
96
|
if (native) return native.mockNativeModule(name, impl);
|
|
@@ -72,6 +115,7 @@ function clearMockFns(obj, visited = /* @__PURE__ */ new Set()) {
|
|
|
72
115
|
}
|
|
73
116
|
}
|
|
74
117
|
function resetAllMocks() {
|
|
118
|
+
restorePresetMockOverrides();
|
|
75
119
|
const native = getNativeControl();
|
|
76
120
|
if (native) return native.resetAllMocks();
|
|
77
121
|
const mock = getMock();
|
|
@@ -110,4 +154,4 @@ function resetAllMocks() {
|
|
|
110
154
|
}
|
|
111
155
|
}
|
|
112
156
|
//#endregion
|
|
113
|
-
export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };
|
|
157
|
+
export { extendPresetMock, mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };
|
|
@@ -287,12 +287,37 @@ interface VitestNativeOptions {
|
|
|
287
287
|
* (e.g. `react-native-reanimated`, `react-native-safe-area-context`) need to
|
|
288
288
|
* be listed here, analogous to Jest's `transformIgnorePatterns` allowlist.
|
|
289
289
|
*
|
|
290
|
+
* The object form adds `exclude`, which names packages the engine must NEVER
|
|
291
|
+
* transform, whatever else would have selected them — auto-detection, a detected
|
|
292
|
+
* package's dependency closure, or the engine's own built-in lists.
|
|
293
|
+
*
|
|
294
|
+
* `exclude` exists because the engine's judgement about what is React Native source
|
|
295
|
+
* is a heuristic, and when it guesses wrong the failure is a parse error deep inside
|
|
296
|
+
* a package the project never named. Build toolchains are the recurring case:
|
|
297
|
+
* compiling one re-enters Babel while it is loading. The engine excludes the ones it
|
|
298
|
+
* knows about, but that list is only as current as the last release — `exclude` is
|
|
299
|
+
* how a project unblocks itself the same day, without waiting for one.
|
|
300
|
+
*
|
|
301
|
+
* Run with `diagnostics: true` to print the packages the engine chose to compile;
|
|
302
|
+
* that list is what `exclude` subtracts from.
|
|
303
|
+
*
|
|
290
304
|
* @example
|
|
291
305
|
* ```ts
|
|
292
306
|
* reactNative({ engine: 'native', transform: ['react-native-reanimated'] })
|
|
307
|
+
*
|
|
308
|
+
* reactNative({
|
|
309
|
+
* engine: 'native',
|
|
310
|
+
* transform: {
|
|
311
|
+
* include: ['react-native-reanimated'],
|
|
312
|
+
* exclude: ['some-build-tool'], // never hand this to the Babel preset
|
|
313
|
+
* },
|
|
314
|
+
* })
|
|
293
315
|
* ```
|
|
294
316
|
*/
|
|
295
|
-
transform?: string[]
|
|
317
|
+
transform?: string[] | {
|
|
318
|
+
include?: string[];
|
|
319
|
+
exclude?: string[];
|
|
320
|
+
};
|
|
296
321
|
/**
|
|
297
322
|
* `engine: 'native'` only. **Experimental.** Run tests in persistent
|
|
298
323
|
* RN-hot workers: React Native's module graph loads once per worker and
|
|
@@ -315,6 +340,15 @@ interface VitestNativeOptions {
|
|
|
315
340
|
* - `preserveGlobals`: exact globalThis property names intentionally owned
|
|
316
341
|
* by resident external libraries. App/test globals are otherwise removed
|
|
317
342
|
* between files. Storybook's preview registry is preserved automatically.
|
|
343
|
+
* - `esmGeneration`: re-evaluate externalized packages a test file `import`s,
|
|
344
|
+
* so their module-level state does not carry into the next file. Node's ESM
|
|
345
|
+
* registry cannot be invalidated, so the loader stamps a per-file generation
|
|
346
|
+
* onto the resolved URL instead. On by default, because without it those
|
|
347
|
+
* packages behave differently under hot than under stock isolation. It costs
|
|
348
|
+
* re-execution: a suite whose files import many externalized (non-React
|
|
349
|
+
* Native) packages measured 55% more wall clock at the extreme — still 9x
|
|
350
|
+
* stock isolation, against 13.9x with it off. Set false to trade that back,
|
|
351
|
+
* accepting that a package holding state across files will keep it.
|
|
318
352
|
*
|
|
319
353
|
* Default: false (each file runs in a fresh worker; RN reloads per file).
|
|
320
354
|
*/
|
|
@@ -322,6 +356,7 @@ interface VitestNativeOptions {
|
|
|
322
356
|
recycleAfterFiles?: number;
|
|
323
357
|
memoryLimit?: number;
|
|
324
358
|
preserveGlobals?: string[];
|
|
359
|
+
esmGeneration?: boolean;
|
|
325
360
|
};
|
|
326
361
|
}
|
|
327
362
|
//#endregion
|
|
@@ -286,12 +286,37 @@ interface VitestNativeOptions {
|
|
|
286
286
|
* (e.g. `react-native-reanimated`, `react-native-safe-area-context`) need to
|
|
287
287
|
* be listed here, analogous to Jest's `transformIgnorePatterns` allowlist.
|
|
288
288
|
*
|
|
289
|
+
* The object form adds `exclude`, which names packages the engine must NEVER
|
|
290
|
+
* transform, whatever else would have selected them — auto-detection, a detected
|
|
291
|
+
* package's dependency closure, or the engine's own built-in lists.
|
|
292
|
+
*
|
|
293
|
+
* `exclude` exists because the engine's judgement about what is React Native source
|
|
294
|
+
* is a heuristic, and when it guesses wrong the failure is a parse error deep inside
|
|
295
|
+
* a package the project never named. Build toolchains are the recurring case:
|
|
296
|
+
* compiling one re-enters Babel while it is loading. The engine excludes the ones it
|
|
297
|
+
* knows about, but that list is only as current as the last release — `exclude` is
|
|
298
|
+
* how a project unblocks itself the same day, without waiting for one.
|
|
299
|
+
*
|
|
300
|
+
* Run with `diagnostics: true` to print the packages the engine chose to compile;
|
|
301
|
+
* that list is what `exclude` subtracts from.
|
|
302
|
+
*
|
|
289
303
|
* @example
|
|
290
304
|
* ```ts
|
|
291
305
|
* reactNative({ engine: 'native', transform: ['react-native-reanimated'] })
|
|
306
|
+
*
|
|
307
|
+
* reactNative({
|
|
308
|
+
* engine: 'native',
|
|
309
|
+
* transform: {
|
|
310
|
+
* include: ['react-native-reanimated'],
|
|
311
|
+
* exclude: ['some-build-tool'], // never hand this to the Babel preset
|
|
312
|
+
* },
|
|
313
|
+
* })
|
|
292
314
|
* ```
|
|
293
315
|
*/
|
|
294
|
-
transform?: string[]
|
|
316
|
+
transform?: string[] | {
|
|
317
|
+
include?: string[];
|
|
318
|
+
exclude?: string[];
|
|
319
|
+
};
|
|
295
320
|
/**
|
|
296
321
|
* `engine: 'native'` only. **Experimental.** Run tests in persistent
|
|
297
322
|
* RN-hot workers: React Native's module graph loads once per worker and
|
|
@@ -314,6 +339,15 @@ interface VitestNativeOptions {
|
|
|
314
339
|
* - `preserveGlobals`: exact globalThis property names intentionally owned
|
|
315
340
|
* by resident external libraries. App/test globals are otherwise removed
|
|
316
341
|
* between files. Storybook's preview registry is preserved automatically.
|
|
342
|
+
* - `esmGeneration`: re-evaluate externalized packages a test file `import`s,
|
|
343
|
+
* so their module-level state does not carry into the next file. Node's ESM
|
|
344
|
+
* registry cannot be invalidated, so the loader stamps a per-file generation
|
|
345
|
+
* onto the resolved URL instead. On by default, because without it those
|
|
346
|
+
* packages behave differently under hot than under stock isolation. It costs
|
|
347
|
+
* re-execution: a suite whose files import many externalized (non-React
|
|
348
|
+
* Native) packages measured 55% more wall clock at the extreme — still 9x
|
|
349
|
+
* stock isolation, against 13.9x with it off. Set false to trade that back,
|
|
350
|
+
* accepting that a package holding state across files will keep it.
|
|
317
351
|
*
|
|
318
352
|
* Default: false (each file runs in a fresh worker; RN reloads per file).
|
|
319
353
|
*/
|
|
@@ -321,6 +355,7 @@ interface VitestNativeOptions {
|
|
|
321
355
|
recycleAfterFiles?: number;
|
|
322
356
|
memoryLimit?: number;
|
|
323
357
|
preserveGlobals?: string[];
|
|
358
|
+
esmGeneration?: boolean;
|
|
324
359
|
};
|
|
325
360
|
}
|
|
326
361
|
//#endregion
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as ReactNativeMock, t as index_d_exports, x as VitestNativeOptions, y as Preset } from "./index-
|
|
1
|
+
import { b as ReactNativeMock, t as index_d_exports, x as VitestNativeOptions, y as Preset } from "./index-CmETArCM.mjs";
|
|
2
2
|
import { Plugin } from "vite";
|
|
3
3
|
//#region src/plugin.d.ts
|
|
4
4
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
|
|
2
|
-
import { a as packageDirOf, c as validateOptions, i as containsPath, l as validatePeerDependency, n as detectEngine, o as packagePatterns, r as REACT_NATIVE_PATH, s as PEER_REQUIREMENTS, t as detectEcosystemPackages, u as warnUnknownOptions } from "./ecosystem-
|
|
2
|
+
import { a as packageDirOf, c as validateOptions, i as containsPath, l as validatePeerDependency, n as detectEngine, o as packagePatterns, r as REACT_NATIVE_PATH, s as PEER_REQUIREMENTS, t as detectEcosystemPackages, u as warnUnknownOptions } from "./ecosystem-Duw40-mO.mjs";
|
|
3
3
|
import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
|
|
4
|
-
import { t as presets_exports } from "./presets-
|
|
4
|
+
import { t as presets_exports } from "./presets-DGProTaA.mjs";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
@@ -27,16 +27,24 @@ const METRO_SOURCE_EXTS = [
|
|
|
27
27
|
"tsx"
|
|
28
28
|
];
|
|
29
29
|
/**
|
|
30
|
-
*
|
|
31
|
-
*
|
|
30
|
+
* Extension-MAJOR, exactly as Metro resolves: for each source extension in order,
|
|
31
|
+
* try the platform variant, then `.native`, then bare — `.ios.js`, `.native.js`,
|
|
32
|
+
* `.js`, `.ios.jsx`, … (metro-resolver's `resolveSourceFile` loops `sourceExts`
|
|
33
|
+
* in the outer loop and the platform variants inside it).
|
|
34
|
+
*
|
|
35
|
+
* This order previously interleaved the other way — every `.ios.*` before any
|
|
36
|
+
* `.native.*` before any bare extension — and the difference is not stylistic:
|
|
37
|
+
* a module shipping `Foo.native.js` beside `Foo.ios.tsx` resolves to
|
|
38
|
+
* `.native.js` under Metro (the `js` round wins before `tsx` is ever tried) but
|
|
39
|
+
* resolved to `.ios.tsx` here, so the test ran a different file than the app
|
|
40
|
+
* ships. The order is asserted against real metro-resolver by
|
|
41
|
+
* tests/metro-resolver-oracle.test.ts, not just against these literals.
|
|
32
42
|
*/
|
|
33
43
|
function extensionsFor(platform) {
|
|
34
44
|
const suffix = platform === "android" ? "android" : "ios";
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
...METRO_SOURCE_EXTS.map((e) => `.${e}`)
|
|
39
|
-
];
|
|
45
|
+
const exts = [];
|
|
46
|
+
for (const e of METRO_SOURCE_EXTS) exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
|
|
47
|
+
return exts;
|
|
40
48
|
}
|
|
41
49
|
//#endregion
|
|
42
50
|
//#region src/resolve.ts
|
|
@@ -213,6 +221,34 @@ function nearestPackageDir(from) {
|
|
|
213
221
|
dir = parent;
|
|
214
222
|
}
|
|
215
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* The `transform` option in either shape: an array of packages to compile, or an
|
|
226
|
+
* object naming those and the ones to leave alone.
|
|
227
|
+
*
|
|
228
|
+
* `exclude` overrides everything — auto-detection, the closure walk, and the engine's
|
|
229
|
+
* built-in toolchain and infrastructure lists. Those built-in lists are names the
|
|
230
|
+
* engine learned from packages that broke, which means they are only ever as current
|
|
231
|
+
* as the last release; `exclude` is the same decision, handed to the project.
|
|
232
|
+
*/
|
|
233
|
+
function normalizeTransformOption(option) {
|
|
234
|
+
const names = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string" && v !== "") : [];
|
|
235
|
+
if (Array.isArray(option)) return {
|
|
236
|
+
include: names(option),
|
|
237
|
+
exclude: []
|
|
238
|
+
};
|
|
239
|
+
if (option && typeof option === "object") {
|
|
240
|
+
const shape = option;
|
|
241
|
+
const exclude = names(shape.exclude);
|
|
242
|
+
return {
|
|
243
|
+
include: names(shape.include).filter((n) => !exclude.includes(n)),
|
|
244
|
+
exclude
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
include: [],
|
|
249
|
+
exclude: []
|
|
250
|
+
};
|
|
251
|
+
}
|
|
216
252
|
function resolvePackageVersion(packageName, projectRoot) {
|
|
217
253
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
218
254
|
try {
|
|
@@ -391,6 +427,7 @@ const RN_EXPORT_NAMES = [
|
|
|
391
427
|
"Alert",
|
|
392
428
|
"Linking",
|
|
393
429
|
"AppState",
|
|
430
|
+
"AssetRegistry",
|
|
394
431
|
"Keyboard",
|
|
395
432
|
"BackHandler",
|
|
396
433
|
"Vibration",
|
|
@@ -682,7 +719,7 @@ function reactNative(options) {
|
|
|
682
719
|
const platform = options?.platform ?? "ios";
|
|
683
720
|
const diagnostics = options?.diagnostics ?? false;
|
|
684
721
|
const requestedEngine = options?.engine ?? "auto";
|
|
685
|
-
const transformPkgs = (options?.transform
|
|
722
|
+
const { include: transformPkgs, exclude: neverTransform } = normalizeTransformOption(options?.transform);
|
|
686
723
|
const hotRuntimeOpt = options?.hotRuntime ?? false;
|
|
687
724
|
const hotRuntime = hotRuntimeOpt !== false;
|
|
688
725
|
const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
|
|
@@ -704,7 +741,7 @@ function reactNative(options) {
|
|
|
704
741
|
const jsxTransform = getJsxTransformConfig(resolvedRoot);
|
|
705
742
|
const decision = detectEngine(requestedEngine, resolvedRoot);
|
|
706
743
|
engine = decision.engine;
|
|
707
|
-
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}
|
|
744
|
+
if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires react-native, '@react-native/babel-preset', and '@babel/core' to resolve from ${resolvedRoot} — missing: ${decision.missing.join(", ")}. React Native projects ship all three by default. Install what's missing (react-native as a dependency, the toolchain as devDependencies), or set engine:'mock' to run without a React Native install.`);
|
|
708
745
|
if (decision.notice) console.warn(decision.notice);
|
|
709
746
|
printEngineBanner(engine, platform, resolvedRoot);
|
|
710
747
|
const env = {
|
|
@@ -717,6 +754,7 @@ function reactNative(options) {
|
|
|
717
754
|
const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
|
|
718
755
|
env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
|
|
719
756
|
if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
|
|
757
|
+
if (hotRuntime && hotRecycle.esmGeneration === false) env.VITEST_NATIVE_HOT_ESM_GEN = "0";
|
|
720
758
|
if (engine === "native") {
|
|
721
759
|
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'.");
|
|
722
760
|
const disabledNative = disabledPresetNames(options?.presets);
|
|
@@ -728,7 +766,7 @@ function reactNative(options) {
|
|
|
728
766
|
if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
|
|
729
767
|
}
|
|
730
768
|
const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
|
|
731
|
-
const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots);
|
|
769
|
+
const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform);
|
|
732
770
|
const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
|
|
733
771
|
const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
|
|
734
772
|
if (projectDirs.length > 0) env.VITEST_NATIVE_PROJECT_DIRS = JSON.stringify(projectDirs);
|
package/dist/native/explain.mjs
CHANGED
|
@@ -44,21 +44,42 @@ export function decorateTransformError(err, file, platform) {
|
|
|
44
44
|
const UNTRANSPILED_SYNTAX =
|
|
45
45
|
/Unexpected token '?<'?|Unexpected identifier|Unexpected reserved word|Missing initializer in const|Unexpected token ':'/;
|
|
46
46
|
|
|
47
|
+
// Node's ReferenceError when a MIXED-SYNTAX file runs: top-level `import` makes the
|
|
48
|
+
// CJS parse fail, Node retries the file as an ES module (require(esm)), and the
|
|
49
|
+
// CommonJS half then dereferences a wrapper variable that ESM scope never defines.
|
|
50
|
+
// Metro compiles both halves, so packages ship this shape — react-native-worklets'
|
|
51
|
+
// lib/module/mock.js ends in `module.exports = ...` under a header of `import`s.
|
|
52
|
+
// It is the runtime sibling of the SyntaxError class above: same cause, same fix,
|
|
53
|
+
// but it parses cleanly and so fails AFTER compilation, as a ReferenceError.
|
|
54
|
+
const ESM_SCOPE_REFERENCE =
|
|
55
|
+
/\b(?:module|exports|require|__dirname|__filename) is not defined in ES module scope/;
|
|
56
|
+
|
|
47
57
|
/**
|
|
48
|
-
* When Node throws
|
|
49
|
-
*
|
|
50
|
-
* untranspiled JSX/Flow/TS
|
|
58
|
+
* When Node throws compiling or running a node_modules file that vitest-native did
|
|
59
|
+
* NOT transform, explain the (very common) real cause: the package ships source
|
|
60
|
+
* only Metro can run — untranspiled JSX/Flow/TS (a SyntaxError), or mixed
|
|
61
|
+
* ESM-import/CommonJS-exports (a ReferenceError from the require(esm) retry) —
|
|
62
|
+
* and needs to be added to `transform: [...]`.
|
|
51
63
|
* Returns a decorated error, or null when the failure doesn't match the pattern.
|
|
52
64
|
*/
|
|
53
65
|
export function explainUntransformedSyntaxError(err, file) {
|
|
54
|
-
if (!err
|
|
55
|
-
|
|
66
|
+
if (!err) return null;
|
|
67
|
+
const matches =
|
|
68
|
+
(err.name === "SyntaxError" && UNTRANSPILED_SYNTAX.test(String(err.message))) ||
|
|
69
|
+
(err.name === "ReferenceError" && ESM_SCOPE_REFERENCE.test(String(err.message)));
|
|
70
|
+
if (!matches) return null;
|
|
56
71
|
const pkg = packageNameFromPath(file);
|
|
57
72
|
if (!pkg) return null;
|
|
58
|
-
const
|
|
73
|
+
const cause =
|
|
74
|
+
err.name === "ReferenceError"
|
|
75
|
+
? `This usually means the package publishes mixed ES-module/CommonJS source ` +
|
|
76
|
+
`that only a bundler like Metro can run.`
|
|
77
|
+
: `This usually means the package publishes untranspiled JSX, Flow, or TypeScript.`;
|
|
78
|
+
const Ctor = err.name === "ReferenceError" ? ReferenceError : SyntaxError;
|
|
79
|
+
const wrapped = new Ctor(
|
|
59
80
|
`[vitest-native] '${pkg}' shipped source Node can't run directly ` +
|
|
60
81
|
`(${err.message} in ${file}).\n` +
|
|
61
|
-
|
|
82
|
+
`${cause} ` +
|
|
62
83
|
`Ask vitest-native to transform it:\n\n` +
|
|
63
84
|
` reactNative({ transform: ['${pkg}'] })\n\n` +
|
|
64
85
|
`in your vitest config. See https://github.com/danfry1/vitest-native` +
|
package/dist/native/globals.mjs
CHANGED
|
@@ -21,7 +21,7 @@ export function installGlobals() {
|
|
|
21
21
|
g.IS_REACT_ACT_ENVIRONMENT = true;
|
|
22
22
|
g.IS_REACT_NATIVE_TEST_ENVIRONMENT = true;
|
|
23
23
|
g.__fbBatchedBridgeConfig = { remoteModuleConfig: [], localModulesConfig: [] };
|
|
24
|
-
g.__vitest_native_module_mocks = g.__vitest_native_module_mocks ||
|
|
24
|
+
g.__vitest_native_module_mocks = g.__vitest_native_module_mocks || Object.create(null);
|
|
25
25
|
|
|
26
26
|
installExpoGlobal(g);
|
|
27
27
|
}
|
|
@@ -71,15 +71,34 @@ function installExpoGlobal(g) {
|
|
|
71
71
|
// setUpJsLogger) call methods like `.addListener` on these, so return a
|
|
72
72
|
// permissive NativeModule stub (EventEmitter methods + no-op for unknown native
|
|
73
73
|
// methods) for any accessed module rather than crashing on `undefined`.
|
|
74
|
+
//
|
|
75
|
+
// Fabricated properties follow two Expo conventions instead of a blanket
|
|
76
|
+
// `() => undefined`:
|
|
77
|
+
// - `*Async` methods return Promises on device, and packages chain on them at
|
|
78
|
+
// import time (expo-notifications: `getRegistrationInfoAsync().then(...)`),
|
|
79
|
+
// so they resolve undefined — matching jest-expo's generated mocks.
|
|
80
|
+
// - PascalCase properties are native classes (SharedObjects) that package JS
|
|
81
|
+
// subclasses (expo-file-system: `class File extends ExpoFileSystem.FileSystemFile`),
|
|
82
|
+
// so they are memoized classes on SharedObject's prototype chain.
|
|
83
|
+
// Explicitly-set properties (spies, overrides) always win.
|
|
74
84
|
const __moduleCache = new Map();
|
|
75
|
-
const makeModuleStub = () =>
|
|
76
|
-
|
|
85
|
+
const makeModuleStub = () => {
|
|
86
|
+
const fabricatedClasses = new Map();
|
|
87
|
+
return new Proxy(new NativeModule(), {
|
|
77
88
|
get(target, prop) {
|
|
78
89
|
if (prop in target) return target[prop];
|
|
79
90
|
if (typeof prop === "symbol") return undefined;
|
|
91
|
+
if (prop.endsWith("Async")) return () => Promise.resolve(undefined);
|
|
92
|
+
if (/^[A-Z]/.test(prop)) {
|
|
93
|
+
if (!fabricatedClasses.has(prop)) {
|
|
94
|
+
fabricatedClasses.set(prop, class extends SharedObject {});
|
|
95
|
+
}
|
|
96
|
+
return fabricatedClasses.get(prop);
|
|
97
|
+
}
|
|
80
98
|
return () => undefined;
|
|
81
99
|
},
|
|
82
100
|
});
|
|
101
|
+
};
|
|
83
102
|
const modules = new Proxy(
|
|
84
103
|
{},
|
|
85
104
|
{
|
package/dist/native/hooks.mjs
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
import Module from "node:module";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs from "node:fs";
|
|
6
|
-
import { transformRN, isFlow } from "./transform.mjs";
|
|
6
|
+
import { transformRN, isFlow, needsTransform } from "./transform.mjs";
|
|
7
7
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
|
-
import { resolvePlatformFile } from "./resolve.mjs";
|
|
8
|
+
import { resolvePlatformFile, resolveDeepPackageFile } from "./resolve.mjs";
|
|
9
9
|
import {
|
|
10
10
|
NODE_MODULES_PATH,
|
|
11
11
|
REACT_NATIVE_PATH,
|
|
@@ -163,7 +163,17 @@ export function installRequireHooks(
|
|
|
163
163
|
reactNativeVersion = "0.0.0",
|
|
164
164
|
assetExts = [],
|
|
165
165
|
) {
|
|
166
|
-
if (globalThis.__vitest_native_require_hooks_installed)
|
|
166
|
+
if (globalThis.__vitest_native_require_hooks_installed) {
|
|
167
|
+
// Install once per worker — but not with a frozen transform list. The hot
|
|
168
|
+
// worker installs the hooks at BOOT, before the setup file has built the
|
|
169
|
+
// preset mocks and can extend the list with preset-shadowed packages (their
|
|
170
|
+
// pass-through entries are compiled only if named here); a pure no-op would
|
|
171
|
+
// pin the boot-time env list forever, and the divergence is hot-only because
|
|
172
|
+
// under stock the setup file IS the first caller. Rebuild the matcher when
|
|
173
|
+
// a later caller brings a different list; hook layers are never stacked.
|
|
174
|
+
globalThis.__vitest_native_require_hooks_update?.(transformPkgs);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
167
177
|
globalThis.__vitest_native_require_hooks_installed = true;
|
|
168
178
|
|
|
169
179
|
// Asset requires (`require('./logo.png')`, `require('./Icon.ttf')`) reaching
|
|
@@ -186,7 +196,16 @@ export function installRequireHooks(
|
|
|
186
196
|
}
|
|
187
197
|
|
|
188
198
|
// Configured third-party packages to also transform (Flow/TS/JSX stripped).
|
|
189
|
-
|
|
199
|
+
// `let` + the updater below: the hot worker installs the hooks at boot with the
|
|
200
|
+
// raw env list, and the setup file re-calls with the preset-extended one.
|
|
201
|
+
let isExtra = buildPkgMatcher(transformPkgs, projectRoot);
|
|
202
|
+
let isExtraKey = JSON.stringify(transformPkgs);
|
|
203
|
+
globalThis.__vitest_native_require_hooks_update = (pkgs) => {
|
|
204
|
+
const key = JSON.stringify(pkgs);
|
|
205
|
+
if (key === isExtraKey) return;
|
|
206
|
+
isExtraKey = key;
|
|
207
|
+
isExtra = buildPkgMatcher(pkgs, projectRoot);
|
|
208
|
+
};
|
|
190
209
|
|
|
191
210
|
// Preset redirect (CJS): when an externalized third-party module require()s a
|
|
192
211
|
// preset package by its bare name (e.g. @gorhom/bottom-sheet → require(
|
|
@@ -273,7 +292,18 @@ export function installRequireHooks(
|
|
|
273
292
|
);
|
|
274
293
|
if (hit) return hit;
|
|
275
294
|
}
|
|
276
|
-
|
|
295
|
+
let resolved;
|
|
296
|
+
try {
|
|
297
|
+
resolved = origResolve.call(this, request, parent, ...rest);
|
|
298
|
+
} catch (err) {
|
|
299
|
+
// RN 0.87's exports map rejects the deep self-references its own Babel
|
|
300
|
+
// preset emits (`react-native/src/private/…`); Metro resolves them via the
|
|
301
|
+
// `react-native-legacy-deep-imports` condition. Mirror Metro by path.
|
|
302
|
+
const fromDir = parent?.filename ? path.dirname(parent.filename) : projectRoot;
|
|
303
|
+
const deep = resolveDeepPackageFile(request, fromDir, platform);
|
|
304
|
+
if (deep === null) throw err;
|
|
305
|
+
resolved = deep;
|
|
306
|
+
}
|
|
277
307
|
checkResolverAgreement(request, resolved);
|
|
278
308
|
checkProjectSourceLoadedByNode(resolved, parent);
|
|
279
309
|
return resolved;
|
|
@@ -289,10 +319,15 @@ export function installRequireHooks(
|
|
|
289
319
|
if (isFlow(src))
|
|
290
320
|
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
291
321
|
} else if (isExtra(norm)) {
|
|
292
|
-
//
|
|
293
|
-
//
|
|
322
|
+
// Selected for compiling — but only compile what Node cannot run as published.
|
|
323
|
+
// `isFlow` is not enough here (TS `import type` and JSX slip past it), and
|
|
324
|
+
// compiling everything is what handed Babel its own toolchain. See
|
|
325
|
+
// needsTransform: V8 answers the question Node is about to ask.
|
|
294
326
|
const src = fs.readFileSync(filename, "utf8");
|
|
295
|
-
|
|
327
|
+
if (needsTransform(filename, src)) {
|
|
328
|
+
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
329
|
+
}
|
|
330
|
+
return origJs(mod, filename);
|
|
296
331
|
}
|
|
297
332
|
if (NODE_MODULES_PATH.test(norm)) {
|
|
298
333
|
// A node_modules package we did NOT transform: when Node's compile throws a
|
package/dist/native/loader.mjs
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs from "node:fs";
|
|
6
|
-
import { transformRN, isFlow, cjsExportNames } from "./transform.mjs";
|
|
6
|
+
import { transformRN, isFlow, cjsExportNames, needsTransform } from "./transform.mjs";
|
|
7
7
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
|
-
import { resolvePlatformFile } from "./resolve.mjs";
|
|
8
|
+
import { resolvePlatformFile, resolveDeepPackageFile } from "./resolve.mjs";
|
|
9
9
|
import {
|
|
10
10
|
NODE_MODULES_PATH,
|
|
11
11
|
REACT_NATIVE_PATH,
|
|
@@ -55,6 +55,59 @@ let presetExports = {};
|
|
|
55
55
|
// Asset file extensions (without leading dot, lower-cased) the loader should stub.
|
|
56
56
|
let assetExtSet = new Set();
|
|
57
57
|
|
|
58
|
+
/**
|
|
59
|
+
* Hot-runtime ESM generation (experimental, `VITEST_NATIVE_HOT_ESM_GEN=1`).
|
|
60
|
+
*
|
|
61
|
+
* Node's ESM registry has no invalidation API, so a package a TEST FILE reaches
|
|
62
|
+
* through `import` keeps its module state for the whole run — the per-file reset
|
|
63
|
+
* can only clear the CommonJS cache. That is the hot runtime's one measured
|
|
64
|
+
* correctness hole at scale (see validation/idiomatic/scale, `extstore`).
|
|
65
|
+
*
|
|
66
|
+
* The registry is keyed by full URL, query included, so stamping a generation onto
|
|
67
|
+
* the URL makes the next file's import a different module and Node evaluates it
|
|
68
|
+
* again. The counter lives in a SharedArrayBuffer because loader hooks run on their
|
|
69
|
+
* own thread; the worker bumps it in the per-file reset.
|
|
70
|
+
*
|
|
71
|
+
* Cost is bounded by ownership: a CommonJS package re-enters through Module._cache,
|
|
72
|
+
* which the reset already drops, so only a thin namespace wrapper is retained per
|
|
73
|
+
* generation. A true-ESM package retains its whole instance — which is why this is
|
|
74
|
+
* measured before it is trusted.
|
|
75
|
+
*/
|
|
76
|
+
let genView = null;
|
|
77
|
+
const generationOf = () => (genView ? Atomics.load(genView, 0) : 0);
|
|
78
|
+
// Modules whose identity must be stable across files: dropping them makes a twin
|
|
79
|
+
// rather than a fresh copy. Mirrors KEEP_RESIDENT in module-reset.mjs.
|
|
80
|
+
const KEEP_RESIDENT =
|
|
81
|
+
/[\\/]node_modules[\\/](react|react-is|react-dom|scheduler|react-reconciler|react-test-renderer|test-renderer|@testing-library[\\/]react-native)[\\/]/;
|
|
82
|
+
// The test stack itself: Vitest's runtime, the chai it asserts through, and this
|
|
83
|
+
// engine. The worker's runtime holds instances of these from boot — the runner's
|
|
84
|
+
// SnapshotClient, chai's extended Assertion, the engine's registry and hooks — and a
|
|
85
|
+
// test file reaches the SAME packages through Node's ESM path. Stamping those
|
|
86
|
+
// resolutions hands the file a twin runtime: `toMatchSnapshot` then asks a
|
|
87
|
+
// SnapshotClient no one set up, `vi.useFakeTimers` flips a copy of the timer state
|
|
88
|
+
// the runner never reads, and matchers extend a chai the expect chain doesn't use.
|
|
89
|
+
//
|
|
90
|
+
// The workspace gates cannot catch a miss here: in-repo, this package and the
|
|
91
|
+
// validation suites resolve OUTSIDE node_modules, so the NODE_MODULES_PATH guard
|
|
92
|
+
// below exempts the engine by accident of layout. Only a packed install — the
|
|
93
|
+
// bake-off apps — puts the whole test stack under node_modules where stamping can
|
|
94
|
+
// reach it. That is how this list was earned: react-native-paper under the hot
|
|
95
|
+
// runtime, 603/678 -> 473/648, every extra failure a twin-runtime symptom.
|
|
96
|
+
const TEST_RUNTIME_RESIDENT =
|
|
97
|
+
/[\\/]node_modules[\\/](vitest|@vitest[\\/][^\\/]+|chai|vitest-native)[\\/]/;
|
|
98
|
+
|
|
99
|
+
/** Should this resolved file carry a generation stamp? */
|
|
100
|
+
function versionable(url) {
|
|
101
|
+
if (!genView || !url.startsWith("file:")) return false;
|
|
102
|
+
const norm = fileURLToPath(url).replace(/\\/g, "/");
|
|
103
|
+
if (!NODE_MODULES_PATH.test(norm)) return false;
|
|
104
|
+
// React Native itself is preloaded once per worker and shared deliberately —
|
|
105
|
+
// re-instantiating it per file would undo the reason the worker stays warm.
|
|
106
|
+
if (REACT_NATIVE_PATH.test(norm) || KEEP_RESIDENT.test(norm)) return false;
|
|
107
|
+
if (TEST_RUNTIME_RESIDENT.test(norm)) return false;
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
|
|
58
111
|
export async function initialize(data) {
|
|
59
112
|
if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
|
|
60
113
|
if (data && data.platform === "android") PLATFORM = "android";
|
|
@@ -63,6 +116,7 @@ export async function initialize(data) {
|
|
|
63
116
|
if (data && data.presetExports) presetExports = data.presetExports;
|
|
64
117
|
if (data && data.assetExts)
|
|
65
118
|
assetExtSet = new Set(data.assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
|
|
119
|
+
if (data && data.hotGenerationBuffer) genView = new Int32Array(data.hotGenerationBuffer);
|
|
66
120
|
}
|
|
67
121
|
|
|
68
122
|
export async function resolve(specifier, context, nextResolve) {
|
|
@@ -115,6 +169,17 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
115
169
|
const hit = resolveExtensionless(path.resolve(path.dirname(parent), specifier));
|
|
116
170
|
if (hit) resolved = { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
117
171
|
}
|
|
172
|
+
// RN 0.87's exports map rejects the deep self-references its own Babel
|
|
173
|
+
// preset emits (react-native/src/private/...); Metro resolves them via its
|
|
174
|
+
// legacy-deep-imports condition. Mirror Metro by path (see resolve.mjs).
|
|
175
|
+
if (!resolved) {
|
|
176
|
+
const deep = resolveDeepPackageFile(
|
|
177
|
+
specifier,
|
|
178
|
+
parent ? path.dirname(parent) : PROJECT_ROOT,
|
|
179
|
+
PLATFORM,
|
|
180
|
+
);
|
|
181
|
+
if (deep) resolved = { url: pathToFileURL(deep).href, shortCircuit: true };
|
|
182
|
+
}
|
|
118
183
|
if (!resolved) throw err;
|
|
119
184
|
}
|
|
120
185
|
|
|
@@ -133,6 +198,16 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
133
198
|
shortCircuit: true,
|
|
134
199
|
};
|
|
135
200
|
}
|
|
201
|
+
|
|
202
|
+
// Stamp the hot generation so the next test file re-evaluates this module rather
|
|
203
|
+
// than reusing the ESM registry's copy. `fileURLToPath` ignores the query, so
|
|
204
|
+
// `load` and every on-disk read below are unaffected.
|
|
205
|
+
if (versionable(resolved.url)) {
|
|
206
|
+
const gen = generationOf();
|
|
207
|
+
if (gen > 0 && !resolved.url.includes("vnhot=")) {
|
|
208
|
+
return { ...resolved, url: `${resolved.url}?vnhot=${gen}`, shortCircuit: true };
|
|
209
|
+
}
|
|
210
|
+
}
|
|
136
211
|
return resolved;
|
|
137
212
|
}
|
|
138
213
|
|
|
@@ -248,6 +323,10 @@ export async function load(url, context, nextLoad) {
|
|
|
248
323
|
// JSX are not installed, so a require here fails with "Unexpected token '<'".
|
|
249
324
|
if (TRANSFORMABLE.test(norm)) {
|
|
250
325
|
const src = fs.readFileSync(file, "utf8");
|
|
326
|
+
// Only compile what Node cannot run as published — see needsTransform. A file V8
|
|
327
|
+
// accepts is handed straight back to Node, which is how the toolchain packages a
|
|
328
|
+
// closure walk drags in stop reaching the Babel preset at all.
|
|
329
|
+
if (!needsTransform(file, src)) return nextLoad(url, context);
|
|
251
330
|
const code = transformRN(file, src, PROJECT_ROOT, PLATFORM);
|
|
252
331
|
const names = cjsExportNames(code);
|
|
253
332
|
return {
|
|
@@ -19,11 +19,16 @@ const UNRESETTABLE = /\.node$/;
|
|
|
19
19
|
* rather than a fresh one.
|
|
20
20
|
*
|
|
21
21
|
* Test files reach these through ESM `import`, which caches them in Node's ESM
|
|
22
|
-
* registry
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
22
|
+
* registry. Dropping the CJS entry therefore does not replace the module; it adds a
|
|
23
|
+
* twin, and the two halves of the test stack stop recognising each other. The symptom
|
|
24
|
+
* is not an error about modules: it is RNTL's matchers failing to see elements that a
|
|
25
|
+
* resident renderer produced.
|
|
26
|
+
*
|
|
27
|
+
* The ESM registry is not reachable from here — it has no invalidation API — but it
|
|
28
|
+
* IS keyed by full URL, and the engine owns the resolve hook, so the loader gives
|
|
29
|
+
* every other externalized package a per-file generation stamp instead (see
|
|
30
|
+
* `versionable` in loader.mjs). The entries below are exempt from that on purpose:
|
|
31
|
+
* for them a fresh instance is the bug, not the fix.
|
|
27
32
|
*
|
|
28
33
|
* Which entries carry weight depends on the RNTL version, so the list is bisected
|
|
29
34
|
* rather than assumed. Measured one entry at a time:
|