vitest-native 0.14.0 → 0.14.1
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/README.md +93 -976
- package/dist/cli.mjs +112 -35
- package/dist/{host-5o48Ujzs.mjs → host-BAAAlSkO.mjs} +91 -2
- package/dist/{index-DqU4YO3D.d.mts → index-aNBCTfA5.d.mts} +8 -6
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/native/hooks.mjs +8 -2
- package/dist/native/loader.mjs +12 -3
- package/dist/native/resolve.mjs +19 -0
- package/dist/presets.d.mts +1 -1
- package/docs/migrating-from-jest.md +6 -4
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { c as detectEcosystemPackages, d as fsModuleCacheOnByDefault, g as unsupportedExpoSdkMessage, h as installedExpoVersion, i as ownVitestPackage, l as detectEngine, o as usesVitePlus, p as PEER_REQUIREMENTS, r as installedViteVersion, v as validatePeerDependency } from "./host-
|
|
2
|
+
import { c as detectEcosystemPackages, d as fsModuleCacheOnByDefault, g as unsupportedExpoSdkMessage, h as installedExpoVersion, i as ownVitestPackage, l as detectEngine, o as usesVitePlus, p as PEER_REQUIREMENTS, r as installedViteVersion, v as validatePeerDependency } from "./host-BAAAlSkO.mjs";
|
|
3
3
|
import { i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, o as presetShadowing, r as PRESET_MODULES, s as testsItself, t as AUTO_DETECT_PRESETS } from "./preset-map-CogjYmSw.mjs";
|
|
4
4
|
import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-Couw0Esx.mjs";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
@@ -85,18 +85,18 @@ const RELATIVE_FILES = [
|
|
|
85
85
|
".babelrc.json"
|
|
86
86
|
];
|
|
87
87
|
/**
|
|
88
|
-
* @babel/core's `standardizeName
|
|
89
|
-
*
|
|
88
|
+
* @babel/core's `standardizeName` (lib/config/files/plugins.js), rule for rule except that a name
|
|
89
|
+
* starting with `.` is taken as a relative path: `foo` →
|
|
90
|
+
* `babel-plugin-foo`, `@babel/foo` → `@babel/plugin-foo` (`@babel/plugin-foo` unchanged),
|
|
91
|
+
* `@scope/foo` → `@scope/babel-plugin-foo`, `@scope` → `@scope/babel-plugin`, `module:foo` →
|
|
92
|
+
* `foo`. A relative or absolute path is returned as written.
|
|
90
93
|
*/
|
|
91
94
|
function normalizeBabelName(name, kind = "plugin") {
|
|
92
|
-
const prefix = `babel-${kind}`;
|
|
93
|
-
if (name.startsWith("module:")) return name.slice(7);
|
|
94
95
|
if (name.startsWith(".") || path.isAbsolute(name)) return name;
|
|
95
|
-
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
return `${prefix}-${name}`;
|
|
96
|
+
const prefix = new RegExp(`^(?!@|module:|[^/]+/|babel-${kind}-)`);
|
|
97
|
+
const babelOrg = new RegExp(`^(@babel/)(?!${kind}-|[^/]+/)`);
|
|
98
|
+
const otherOrg = new RegExp(`^(@(?!babel/)[^/]+/)(?![^/]*babel-${kind}(?:-|/|$)|[^/]+/)`);
|
|
99
|
+
return name.replace(prefix, `babel-${kind}-`).replace(babelOrg, `$1${kind}-`).replace(otherOrg, `$1babel-${kind}-`).replace(/^(@(?!babel$)[^/]+)$/, `$1/babel-${kind}`).replace(/^module:/, "");
|
|
100
100
|
}
|
|
101
101
|
function entryOf(item, kind) {
|
|
102
102
|
const [target, options] = Array.isArray(item) ? item : [item, void 0];
|
|
@@ -162,6 +162,54 @@ function entriesOf(config, key) {
|
|
|
162
162
|
...array(config.overrides)
|
|
163
163
|
].flatMap((s) => array(s?.[key]));
|
|
164
164
|
}
|
|
165
|
+
/** Truthy in the sense Babel's `lazy` option is: `true`, a list of names, or a predicate. */
|
|
166
|
+
const enablesLazy = (value) => value === true || typeof value === "function" || Array.isArray(value) && value.length > 0;
|
|
167
|
+
/** The option bags babel-preset-expo merges for a native platform (its getOptions). */
|
|
168
|
+
function expoNativeOptions(options) {
|
|
169
|
+
if (!options || typeof options !== "object") return [];
|
|
170
|
+
const o = options;
|
|
171
|
+
return [
|
|
172
|
+
o,
|
|
173
|
+
o.native,
|
|
174
|
+
o.ios,
|
|
175
|
+
o.android
|
|
176
|
+
].filter((bag) => !!bag && typeof bag === "object");
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Settings that make babel-jest compile `import` into a `require()` run on first use, so a
|
|
180
|
+
* module a test never touches is never evaluated under Jest. Under vitest-native project
|
|
181
|
+
* source is compiled by Vite and its imports are evaluated when the file loads.
|
|
182
|
+
*
|
|
183
|
+
* - babel-preset-expo `lazyImports` (top level or under `native`/`ios`/`android`), passed on as
|
|
184
|
+
* - @react-native/babel-preset `lazyImportExportTransform`, which sets
|
|
185
|
+
* - @babel/plugin-transform-modules-commonjs `lazy`.
|
|
186
|
+
* - An inline-requires plugin (babel-preset-fbjs's, Metro's), which does the same for `require`.
|
|
187
|
+
*
|
|
188
|
+
* With no setting, @react-native/babel-preset makes only a fixed list of React Native's own
|
|
189
|
+
* modules lazy, which tests do not notice, so that is not reported.
|
|
190
|
+
*/
|
|
191
|
+
function lazyImportSettings(presets, plugins) {
|
|
192
|
+
const found = [];
|
|
193
|
+
for (const preset of presets) if (preset.name === "babel-preset-expo") {
|
|
194
|
+
if (expoNativeOptions(preset.options).some((bag) => enablesLazy(bag.lazyImports))) found.push(`${preset.written} lazyImports`);
|
|
195
|
+
} else if (/^(@react-native\/babel-preset|metro-react-native-babel-preset)$/.test(preset.name)) {
|
|
196
|
+
const options = preset.options ?? {};
|
|
197
|
+
if (enablesLazy(options.lazyImportExportTransform)) found.push(`${preset.written} lazyImportExportTransform`);
|
|
198
|
+
}
|
|
199
|
+
for (const plugin of plugins) if (plugin.name === "@babel/plugin-transform-modules-commonjs") {
|
|
200
|
+
const options = plugin.options ?? {};
|
|
201
|
+
if (enablesLazy(options.lazy)) found.push(`${plugin.written} lazy`);
|
|
202
|
+
} else if (/inline-requires/.test(plugin.name)) found.push(plugin.written);
|
|
203
|
+
return [...new Set(found)];
|
|
204
|
+
}
|
|
205
|
+
/** For a config that could only be read as text: the preset options, by name (quoted or not). */
|
|
206
|
+
function lazyImportSettingsInText(text) {
|
|
207
|
+
const found = [];
|
|
208
|
+
if (/\blazyImports["']?\s*:\s*(?!(?:false|null|undefined)\b)\S/.test(text)) found.push("lazyImports");
|
|
209
|
+
if (/\blazyImportExportTransform["']?\s*:\s*(?!(?:false|null|undefined)\b)\S/.test(text)) found.push("lazyImportExportTransform");
|
|
210
|
+
if (/inline-requires/.test(text)) found.push("inline requires");
|
|
211
|
+
return found;
|
|
212
|
+
}
|
|
165
213
|
function readBabelConfig(root) {
|
|
166
214
|
const found = [];
|
|
167
215
|
for (const group of [PROJECT_FILES, RELATIVE_FILES]) {
|
|
@@ -186,18 +234,21 @@ function readBabelConfig(root) {
|
|
|
186
234
|
source: null,
|
|
187
235
|
evaluated: false,
|
|
188
236
|
plugins: [],
|
|
189
|
-
presets: []
|
|
237
|
+
presets: [],
|
|
238
|
+
lazyImports: []
|
|
190
239
|
};
|
|
191
240
|
const plugins = [];
|
|
192
|
-
const
|
|
241
|
+
const presetEntries = [];
|
|
242
|
+
const lazyInText = [];
|
|
193
243
|
let evaluated = true;
|
|
194
244
|
for (const { raw, text } of found) {
|
|
195
245
|
if (raw && typeof raw === "object") {
|
|
196
246
|
plugins.push(...entriesOf(raw, "plugins").map((p) => entryOf(p, "plugin")));
|
|
197
|
-
|
|
247
|
+
presetEntries.push(...entriesOf(raw, "presets").map((p) => entryOf(p, "preset")));
|
|
198
248
|
continue;
|
|
199
249
|
}
|
|
200
250
|
evaluated = false;
|
|
251
|
+
lazyInText.push(...lazyImportSettingsInText(text));
|
|
201
252
|
for (const written of new Set([...text.matchAll(/["'`]([^"'`\s]+)["'`]/g)].map((m) => m[1]))) {
|
|
202
253
|
const name = normalizeBabelName(written);
|
|
203
254
|
if (KNOWN_PLUGINS.some((known) => known.names.includes(name))) plugins.push({
|
|
@@ -210,7 +261,8 @@ function readBabelConfig(root) {
|
|
|
210
261
|
source: found.map((f) => f.source).join(" + "),
|
|
211
262
|
evaluated,
|
|
212
263
|
plugins,
|
|
213
|
-
presets
|
|
264
|
+
presets: presetEntries.map((p) => p.name),
|
|
265
|
+
lazyImports: [.../* @__PURE__ */ new Set([...lazyImportSettings(presetEntries, plugins), ...lazyInText])]
|
|
214
266
|
};
|
|
215
267
|
}
|
|
216
268
|
/** Why a worklet plugin is not needed — only when the preset replacing its library is active. */
|
|
@@ -1463,13 +1515,41 @@ function untranspiledFile(root, pkg) {
|
|
|
1463
1515
|
* so that a migrated project collects the same test files with the same settings
|
|
1464
1516
|
* without hand edits.
|
|
1465
1517
|
*/
|
|
1518
|
+
/**
|
|
1519
|
+
* Jest 30's lookup order for `jest.config.*` (jest-config's JEST_CONFIG_EXT_ORDER; Jest 29's is
|
|
1520
|
+
* the same without .mts and .cts). Jest refuses to run when more than one exists, so the order
|
|
1521
|
+
* only decides which one migrate reports in that case.
|
|
1522
|
+
*/
|
|
1523
|
+
const JEST_CONFIG_EXTENSIONS = [
|
|
1524
|
+
".js",
|
|
1525
|
+
".ts",
|
|
1526
|
+
".mjs",
|
|
1527
|
+
".mts",
|
|
1528
|
+
".cjs",
|
|
1529
|
+
".cts",
|
|
1530
|
+
".json"
|
|
1531
|
+
];
|
|
1532
|
+
/**
|
|
1533
|
+
* Loads a Jest config file the way Node would run it. TypeScript configs (.ts, .mts, .cts)
|
|
1534
|
+
* load through Node's own type stripping, which is on by default from Node 22.18 and 23.6;
|
|
1535
|
+
* ES module configs (.mjs, .mts, and .js/.ts in a "type": "module" package) through
|
|
1536
|
+
* `require()` of ES modules. Jest itself loads a TypeScript config through ts-node and falls
|
|
1537
|
+
* back to `import()`, so a config that relies on either (extensionless relative imports,
|
|
1538
|
+
* `enum`, path aliases, top-level `await`) is reported with Node's reason rather than guessed at.
|
|
1539
|
+
*/
|
|
1466
1540
|
function loadConfigFile(root, file) {
|
|
1467
1541
|
const abs = path.resolve(root, file);
|
|
1468
1542
|
const name = path.relative(root, abs).split(path.sep).join("/") || file;
|
|
1469
1543
|
if (!fs.existsSync(abs)) return null;
|
|
1470
|
-
if (!/\.(
|
|
1544
|
+
if (!/\.(?:[cm]?[jt]s|json)$/.test(abs)) return {
|
|
1471
1545
|
source: name,
|
|
1472
|
-
config: null
|
|
1546
|
+
config: null,
|
|
1547
|
+
error: "not a JavaScript, TypeScript or JSON file"
|
|
1548
|
+
};
|
|
1549
|
+
if (/\.[cm]?ts$/.test(abs) && !process.features.typescript) return {
|
|
1550
|
+
source: name,
|
|
1551
|
+
config: null,
|
|
1552
|
+
error: `Node ${process.version} does not load TypeScript by itself; run migrate on Node 22.18 or later`
|
|
1473
1553
|
};
|
|
1474
1554
|
try {
|
|
1475
1555
|
const req = createRequire(path.join(root, "package.json"));
|
|
@@ -1477,16 +1557,23 @@ function loadConfigFile(root, file) {
|
|
|
1477
1557
|
const config = loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
|
|
1478
1558
|
if (typeof config === "function") return {
|
|
1479
1559
|
source: name,
|
|
1480
|
-
config: null
|
|
1560
|
+
config: null,
|
|
1561
|
+
error: "it exports a function, which Jest calls to build the config; migrate reads only a config object"
|
|
1562
|
+
};
|
|
1563
|
+
if (!config || typeof config !== "object") return {
|
|
1564
|
+
source: name,
|
|
1565
|
+
config: null,
|
|
1566
|
+
error: "it does not export a config object"
|
|
1481
1567
|
};
|
|
1482
1568
|
return {
|
|
1483
1569
|
source: name,
|
|
1484
1570
|
config
|
|
1485
1571
|
};
|
|
1486
|
-
} catch {
|
|
1572
|
+
} catch (error) {
|
|
1487
1573
|
return {
|
|
1488
1574
|
source: name,
|
|
1489
|
-
config: null
|
|
1575
|
+
config: null,
|
|
1576
|
+
error: error instanceof Error ? error.message.split("\n")[0] : String(error)
|
|
1490
1577
|
};
|
|
1491
1578
|
}
|
|
1492
1579
|
}
|
|
@@ -1495,22 +1582,10 @@ function loadJestConfig(root, explicit) {
|
|
|
1495
1582
|
const loaded = loadConfigFile(root, explicit);
|
|
1496
1583
|
if (loaded) return loaded;
|
|
1497
1584
|
}
|
|
1498
|
-
for (const
|
|
1499
|
-
|
|
1500
|
-
"jest.config.cjs",
|
|
1501
|
-
"jest.config.json"
|
|
1502
|
-
]) {
|
|
1503
|
-
const loaded = loadConfigFile(root, name);
|
|
1585
|
+
for (const extension of JEST_CONFIG_EXTENSIONS) {
|
|
1586
|
+
const loaded = loadConfigFile(root, `jest.config${extension}`);
|
|
1504
1587
|
if (loaded) return loaded;
|
|
1505
1588
|
}
|
|
1506
|
-
for (const name of [
|
|
1507
|
-
"jest.config.mjs",
|
|
1508
|
-
"jest.config.ts",
|
|
1509
|
-
"jest.config.mts"
|
|
1510
|
-
]) if (fs.existsSync(path.join(root, name))) return {
|
|
1511
|
-
source: name,
|
|
1512
|
-
config: null
|
|
1513
|
-
};
|
|
1514
1589
|
try {
|
|
1515
1590
|
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
1516
1591
|
if (pkg.jest && typeof pkg.jest === "object") return {
|
|
@@ -1609,9 +1684,10 @@ function analyzeJestConfig(root) {
|
|
|
1609
1684
|
}
|
|
1610
1685
|
} catch {}
|
|
1611
1686
|
const explicitConfig = scriptFlags?.flags.get("config") ?? scriptFlags?.flags.get("c");
|
|
1612
|
-
const { source, config } = loadJestConfig(root, typeof explicitConfig === "string" ? explicitConfig : void 0);
|
|
1687
|
+
const { source, config, error: configError } = loadJestConfig(root, typeof explicitConfig === "string" ? explicitConfig : void 0);
|
|
1613
1688
|
const automatic = [];
|
|
1614
1689
|
const attention = [];
|
|
1690
|
+
if (source && configError) attention.push(`${source} could not be loaded (${configError}), so none of its settings are in the suggested config; carry them over by hand.`);
|
|
1615
1691
|
const presetCovered = [];
|
|
1616
1692
|
const dropped = [];
|
|
1617
1693
|
const testEntries = [`globals: true`, `environment: 'node'`];
|
|
@@ -1872,6 +1948,7 @@ function analyzeJestConfig(root) {
|
|
|
1872
1948
|
}
|
|
1873
1949
|
for (const p of classified.filter((c) => c.verdict === "unneeded")) dropped.push(`${babel.source}: ${p.written} — ${p.reason}`);
|
|
1874
1950
|
for (const p of classified.filter((c) => c.verdict === "unknown")) attention.push(`${babel.source}: ${p.reason}`);
|
|
1951
|
+
if (babel.lazyImports.length) attention.push(`${babel.source}: ${babel.lazyImports.join(", ")} — under Jest a package import ran only when the test first used it; here every import runs when its file loads. A module a test never touched is now evaluated, so a partial jest.mock of something it needs can fail (e.g. "requireOptionalNativeModule is not a function"). Give such a mock the rest of the module: jest.mock('x', () => ({ ...jest.requireActual('x'), ... })).`);
|
|
1875
1952
|
if (!babel.evaluated) attention.push(`${babel.source} could not be evaluated, so only plugins recognized by name are listed; review it for others.`);
|
|
1876
1953
|
}
|
|
1877
1954
|
if (transformPkgs.length) pluginOptions.unshift(`transform: [${transformPkgs.map((p) => JSON.stringify(p)).join(", ")}]`);
|
|
@@ -1961,7 +2038,7 @@ function migrationNextStep(report) {
|
|
|
1961
2038
|
function renderMigrationReport(report, { write = false } = {}) {
|
|
1962
2039
|
const lines = [];
|
|
1963
2040
|
if (!report.source) {
|
|
1964
|
-
lines.push("✗ no Jest configuration found (package.json#jest or jest.config.{js,cjs,json}).", " Starting fresh? Run `vitest-native init` instead.");
|
|
2041
|
+
lines.push("✗ no Jest configuration found (package.json#jest or jest.config.{js,ts,mjs,cjs,mts,cts,json}).", " Starting fresh? Run `vitest-native init` instead.");
|
|
1965
2042
|
return lines;
|
|
1966
2043
|
}
|
|
1967
2044
|
lines.push(`Analyzed ${report.source}`, "");
|
|
@@ -440,6 +440,91 @@ function hasReactNativeBuild(manifest) {
|
|
|
440
440
|
function publishesOnlyEsm(manifest) {
|
|
441
441
|
return manifest.type === "module" && !hasReactNativeBuild(manifest);
|
|
442
442
|
}
|
|
443
|
+
const SPECIFIER = /(?:\brequire\s*\(\s*|\bimport\s*\(\s*|\bfrom\s*|\bimport\s*)["']([^"'\n]+)["']/g;
|
|
444
|
+
const COMMENT = /\/\*[\s\S]*?\*\/|(^|[^:"'`\\])\/\/[^\n]*/g;
|
|
445
|
+
const TYPE_ONLY = /\b(?:import|export)\s+type\b[^;]*?\bfrom\s*["'][^"']+["']/g;
|
|
446
|
+
const RUNTIME_EXTENSIONS = [
|
|
447
|
+
".native.js",
|
|
448
|
+
".ios.js",
|
|
449
|
+
".js",
|
|
450
|
+
".mjs",
|
|
451
|
+
".cjs",
|
|
452
|
+
".jsx",
|
|
453
|
+
".native.ts",
|
|
454
|
+
".ios.ts",
|
|
455
|
+
".ts",
|
|
456
|
+
".native.tsx",
|
|
457
|
+
".ios.tsx",
|
|
458
|
+
".tsx"
|
|
459
|
+
];
|
|
460
|
+
const MAX_RUNTIME_FILES = 5e3;
|
|
461
|
+
const PACKAGE_SPECIFIER = /^(?:@[\w.-]+\/)?[\w][\w.-]*(?:\/|$)/;
|
|
462
|
+
const runtimeMemo = /* @__PURE__ */ new Map();
|
|
463
|
+
/** The file a relative specifier names from `fromDir`, as Metro and Node find it, or null. */
|
|
464
|
+
function runtimeFile(base) {
|
|
465
|
+
const isFile = (file) => fs.statSync(file, { throwIfNoEntry: false })?.isFile() === true;
|
|
466
|
+
if (isFile(base)) return base;
|
|
467
|
+
for (const ext of RUNTIME_EXTENSIONS) if (isFile(base + ext)) return base + ext;
|
|
468
|
+
for (const ext of RUNTIME_EXTENSIONS) {
|
|
469
|
+
const index = path.join(base, `index${ext}`);
|
|
470
|
+
if (isFile(index)) return index;
|
|
471
|
+
}
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
/** Every string target of a manifest's `exports` root (all conditions), or none. */
|
|
475
|
+
function exportTargets(exportsField) {
|
|
476
|
+
if (typeof exportsField === "string") return [exportsField];
|
|
477
|
+
if (!exportsField || typeof exportsField !== "object") return [];
|
|
478
|
+
const node = exportsField;
|
|
479
|
+
const root = "." in node ? node["."] : Object.keys(node).every((k) => !k.startsWith(".")) ? node : null;
|
|
480
|
+
const out = [];
|
|
481
|
+
const collect = (value) => {
|
|
482
|
+
if (typeof value === "string") out.push(value);
|
|
483
|
+
else if (value && typeof value === "object") Object.values(value).forEach(collect);
|
|
484
|
+
};
|
|
485
|
+
collect(root);
|
|
486
|
+
return out;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* The packages a package loads when it runs, by name: the bare specifiers in the files
|
|
490
|
+
* reachable from its runtime entries (its `react-native` field, `main` and `exports`
|
|
491
|
+
* root) through relative requires and imports, with comments and type-only imports left
|
|
492
|
+
* out. Its config plugin, scripts and type declarations are not reached, so a package
|
|
493
|
+
* that names another only there (expo-constants' `expo`, from `expo/config`) does not
|
|
494
|
+
* load it. Read once per directory and process. For the peer edge only (see the closure
|
|
495
|
+
* walk).
|
|
496
|
+
*/
|
|
497
|
+
function runtimeImports(dir, manifest) {
|
|
498
|
+
let names = runtimeMemo.get(dir);
|
|
499
|
+
if (names) return names;
|
|
500
|
+
names = /* @__PURE__ */ new Set();
|
|
501
|
+
const entries = [
|
|
502
|
+
typeof manifest["react-native"] === "string" ? manifest["react-native"] : null,
|
|
503
|
+
typeof manifest.main === "string" ? manifest.main : null,
|
|
504
|
+
...exportTargets(manifest.exports)
|
|
505
|
+
].filter((entry) => entry !== null);
|
|
506
|
+
if (entries.length === 0) entries.push("index");
|
|
507
|
+
const pending = entries.map((entry) => runtimeFile(path.resolve(dir, entry))).filter((file) => file !== null && containsPath(dir, file));
|
|
508
|
+
const seen = /* @__PURE__ */ new Set();
|
|
509
|
+
while (pending.length > 0 && seen.size < MAX_RUNTIME_FILES) {
|
|
510
|
+
const file = pending.pop();
|
|
511
|
+
if (seen.has(file) || file.endsWith(".json")) continue;
|
|
512
|
+
seen.add(file);
|
|
513
|
+
const code = fs.readFileSync(file, "utf8").replace(COMMENT, "$1").replace(TYPE_ONLY, "");
|
|
514
|
+
for (const match of code.matchAll(SPECIFIER)) {
|
|
515
|
+
const specifier = match[1];
|
|
516
|
+
if (specifier.startsWith(".")) {
|
|
517
|
+
const target = runtimeFile(path.resolve(path.dirname(file), specifier));
|
|
518
|
+
if (target !== null && containsPath(dir, target) && !NODE_MODULES_DIR.test(path.relative(dir, target))) pending.push(target);
|
|
519
|
+
} else if (PACKAGE_SPECIFIER.test(specifier)) {
|
|
520
|
+
const parts = specifier.split("/");
|
|
521
|
+
names.add(specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
runtimeMemo.set(dir, names);
|
|
526
|
+
return names;
|
|
527
|
+
}
|
|
443
528
|
/** Manifest fields that make a package part of the React Native ecosystem. */
|
|
444
529
|
function dependsOnReactNative(manifest) {
|
|
445
530
|
for (const field of ["dependencies", "peerDependencies"]) {
|
|
@@ -609,6 +694,7 @@ function fixedReplacement(replacement, regExp) {
|
|
|
609
694
|
* `reachedPaths` adds the workspace members an alias reaches; see ReachedPackages.
|
|
610
695
|
*/
|
|
611
696
|
function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets, dirOf = dependencyDirOf, { reachedPaths = [], onReachedUndeclared } = {}) {
|
|
697
|
+
runtimeMemo.clear();
|
|
612
698
|
const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
|
|
613
699
|
const shadowed = Object.entries(AUTO_DETECT_PRESETS).filter(([, presetName]) => activePresets === void 0 || activePresets.includes(presetName)).map(([pkg]) => pkg);
|
|
614
700
|
const skip = /* @__PURE__ */ new Set([
|
|
@@ -764,10 +850,13 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], nev
|
|
|
764
850
|
if (admits(installed)) reach(dep, installed);
|
|
765
851
|
}
|
|
766
852
|
const peers = pkg.manifest.peerDependencies;
|
|
853
|
+
const peersMeta = pkg.manifest.peerDependenciesMeta;
|
|
767
854
|
for (const peer of peers && typeof peers === "object" ? Object.keys(peers) : []) {
|
|
768
|
-
if (walked.has(peer) || excluded(peer)
|
|
855
|
+
if (walked.has(peer) || excluded(peer)) continue;
|
|
769
856
|
const installed = dependencyOf(pkg, peer);
|
|
770
|
-
if (installed
|
|
857
|
+
if (!installed || !admits(installed)) continue;
|
|
858
|
+
const loadedReactNativePeer = !detectedSet.has(peer) && peersMeta?.[peer]?.optional !== true && dependsOnReactNative(installed.manifest) && runtimeImports(pkg.dir, pkg.manifest).has(peer);
|
|
859
|
+
if (detectedSet.has(peer) || loadedReactNativePeer) reach(peer, installed);
|
|
771
860
|
}
|
|
772
861
|
}
|
|
773
862
|
};
|
|
@@ -321,10 +321,12 @@ interface VitestNativeOptions {
|
|
|
321
321
|
/**
|
|
322
322
|
* `engine: 'native'` only. Names of additional node_modules packages whose
|
|
323
323
|
* source the native engine should transform (Flow/TS/JSX stripped) as it
|
|
324
|
-
* loads them.
|
|
325
|
-
*
|
|
326
|
-
*
|
|
327
|
-
*
|
|
324
|
+
* loads them. Packages the project depends on that declare `react-native` as
|
|
325
|
+
* a dependency or peer dependency, and their runtime dependencies, are
|
|
326
|
+
* detected and transformed without being listed; list a package here when it
|
|
327
|
+
* ships untranspiled source but is not detected, as you would add it to
|
|
328
|
+
* Jest's `transformIgnorePatterns` allowlist. A listed package's own
|
|
329
|
+
* dependencies are transformed too.
|
|
328
330
|
*
|
|
329
331
|
* The object form adds `exclude`, which names packages the engine must NEVER
|
|
330
332
|
* transform, whatever else would have selected them — auto-detection, a detected
|
|
@@ -342,12 +344,12 @@ interface VitestNativeOptions {
|
|
|
342
344
|
*
|
|
343
345
|
* @example
|
|
344
346
|
* ```ts
|
|
345
|
-
* reactNative({ engine: 'native', transform: ['
|
|
347
|
+
* reactNative({ engine: 'native', transform: ['some-untranspiled-lib'] })
|
|
346
348
|
*
|
|
347
349
|
* reactNative({
|
|
348
350
|
* engine: 'native',
|
|
349
351
|
* transform: {
|
|
350
|
-
* include: ['
|
|
352
|
+
* include: ['some-untranspiled-lib'],
|
|
351
353
|
* exclude: ['some-build-tool'], // never hand this to the Babel preset
|
|
352
354
|
* },
|
|
353
355
|
* })
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as VitestNativeOptions, S as ReactNativeMock, t as index_d_exports, x as Preset } from "./index-
|
|
1
|
+
import { C as VitestNativeOptions, S as ReactNativeMock, t as index_d_exports, x as Preset } from "./index-aNBCTfA5.mjs";
|
|
2
2
|
import { Plugin } from "vite";
|
|
3
3
|
/**
|
|
4
4
|
* Preset names switched off by the object form of the `presets` option.
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as validateOptions, a as runningVite, c as detectEcosystemPackages, f as shouldDefaultFsModuleCache, g as unsupportedExpoSdkMessage, h as installedExpoVersion, i as ownVitestPackage, l as detectEngine, m as SUPPORTED_EXPO_SDKS, n as assertHotWorkerLoadsRunningVitest, p as PEER_REQUIREMENTS, s as aliasReachedPaths, t as assertHostResolvesRunningVitest, u as fsModuleCacheKey, v as validatePeerDependency, y as warnUnknownOptions } from "./host-
|
|
1
|
+
import { _ as validateOptions, a as runningVite, c as detectEcosystemPackages, f as shouldDefaultFsModuleCache, g as unsupportedExpoSdkMessage, h as installedExpoVersion, i as ownVitestPackage, l as detectEngine, m as SUPPORTED_EXPO_SDKS, n as assertHotWorkerLoadsRunningVitest, p as PEER_REQUIREMENTS, s as aliasReachedPaths, t as assertHostResolvesRunningVitest, u as fsModuleCacheKey, v as validatePeerDependency, y as warnUnknownOptions } from "./host-BAAAlSkO.mjs";
|
|
2
2
|
import { M as BUILT_IN_PRESET, t as presets_exports } from "./presets-CXDyg51l.mjs";
|
|
3
3
|
import { a as presetForInstalled, i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, r as PRESET_MODULES, t as AUTO_DETECT_PRESETS } from "./preset-map-CogjYmSw.mjs";
|
|
4
4
|
import { t as workerVitestMismatch } from "./worker-vitest-CILPFeRX.mjs";
|
package/dist/native/hooks.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import fs from "node:fs";
|
|
|
8
8
|
import { heldTransform, transformRN, isFlow, needsTransform } from "./transform.mjs";
|
|
9
9
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
10
10
|
import {
|
|
11
|
+
hasKnownExtension,
|
|
11
12
|
resolvePlatformFile,
|
|
12
13
|
resolveRelativePlatformFile,
|
|
13
14
|
resolveDeepPackageFile,
|
|
@@ -457,7 +458,7 @@ export function installRequireHooks(
|
|
|
457
458
|
if (!parent?.filename || NODE_MODULES_PATH.test(parent.filename)) return null;
|
|
458
459
|
const expanded = expandAlias(request, requireAliases);
|
|
459
460
|
if (expanded === request) return null;
|
|
460
|
-
if (path.isAbsolute(expanded) && !
|
|
461
|
+
if (path.isAbsolute(expanded) && !hasKnownExtension(expanded, activeSourceExts, assetExtSet)) {
|
|
461
462
|
const hit = resolvePlatformFile(expanded, platform, activeSourceExts);
|
|
462
463
|
if (hit) return hit;
|
|
463
464
|
}
|
|
@@ -593,7 +594,12 @@ export function installRequireHooks(
|
|
|
593
594
|
}
|
|
594
595
|
// Relative, extensionless: Metro's platform order for every parent, app source
|
|
595
596
|
// included (`./PlatformInfo` → `index.native.ts` before `index.ts`).
|
|
596
|
-
if (
|
|
597
|
+
if (
|
|
598
|
+
!resolved &&
|
|
599
|
+
parent?.filename &&
|
|
600
|
+
request.startsWith(".") &&
|
|
601
|
+
!hasKnownExtension(request, activeSourceExts, assetExtSet)
|
|
602
|
+
) {
|
|
597
603
|
resolved = resolveRelativePlatformFile(request, parent.filename, platform, activeSourceExts);
|
|
598
604
|
if (resolved) resolved = asNodeResolves(resolved);
|
|
599
605
|
}
|
package/dist/native/loader.mjs
CHANGED
|
@@ -14,7 +14,12 @@ import {
|
|
|
14
14
|
} from "./transform.mjs";
|
|
15
15
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
16
16
|
import { nativeAssetModuleSource } from "./assets.mjs";
|
|
17
|
-
import {
|
|
17
|
+
import {
|
|
18
|
+
extensionsFor,
|
|
19
|
+
hasKnownExtension,
|
|
20
|
+
resolveRelativePlatformFile,
|
|
21
|
+
resolveDeepPackageFile,
|
|
22
|
+
} from "./resolve.mjs";
|
|
18
23
|
import {
|
|
19
24
|
NODE_MODULES_PATH,
|
|
20
25
|
containsPath,
|
|
@@ -300,7 +305,7 @@ function resolveBefore(specifier, context) {
|
|
|
300
305
|
parent &&
|
|
301
306
|
(NODE_MODULES_PATH.test(parent) || ownership.isReactNativeFile(parent) || isExtra(parent)) &&
|
|
302
307
|
specifier.startsWith(".") &&
|
|
303
|
-
!
|
|
308
|
+
!hasKnownExtension(specifier, SOURCE_EXTS, assetExtSet)
|
|
304
309
|
) {
|
|
305
310
|
const hit = resolveRelativePlatformFile(specifier, parent, PLATFORM, SOURCE_EXTS);
|
|
306
311
|
// Not returned directly: `json` is a Metro source extension, so this can now
|
|
@@ -317,7 +322,11 @@ function resolveRecover(err, specifier, parent) {
|
|
|
317
322
|
// Fallback: an extensionless relative import that Node's ESM resolver rejected
|
|
318
323
|
// but a bundler (Metro) would accept. Common in externalized RN libs shipping
|
|
319
324
|
// ESM with extensionless imports. Resolve it on disk ourselves.
|
|
320
|
-
if (
|
|
325
|
+
if (
|
|
326
|
+
parent &&
|
|
327
|
+
specifier.startsWith(".") &&
|
|
328
|
+
!hasKnownExtension(specifier, SOURCE_EXTS, assetExtSet)
|
|
329
|
+
) {
|
|
321
330
|
const hit = resolveExtensionless(path.resolve(path.dirname(parent), specifier));
|
|
322
331
|
if (hit) resolved = { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
323
332
|
}
|
package/dist/native/resolve.mjs
CHANGED
|
@@ -185,6 +185,25 @@ export function resolvePlatformFile(absBase, platform = "ios", sourceExts = METR
|
|
|
185
185
|
* `path.resolve` drops a trailing separator, and with it the request's meaning: Node
|
|
186
186
|
* and Metro both resolve `./lib/` to the directory, never to a sibling `lib.ts`.
|
|
187
187
|
*/
|
|
188
|
+
// Extensions a request always names as its own, whatever the source and asset lists say.
|
|
189
|
+
const EXPLICIT_EXTS = new Set(["js", "mjs", "cjs", "json", "node"]);
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Whether `request` ends in an extension, as Metro decides it: a known source or asset
|
|
193
|
+
* extension (or one Node always treats as explicit), not anything after the last dot.
|
|
194
|
+
* `./Linking.types` names no extension, so it is looked up as Linking.types.js and the
|
|
195
|
+
* rest; `path.extname` would have read `.types` and stopped the lookup (#506).
|
|
196
|
+
*/
|
|
197
|
+
export function hasKnownExtension(request, sourceExts, assetExts) {
|
|
198
|
+
const ext = path.extname(request).slice(1).toLowerCase();
|
|
199
|
+
if (ext === "") return false;
|
|
200
|
+
if (EXPLICIT_EXTS.has(ext)) return true;
|
|
201
|
+
if (sourceExts.some((source) => String(source).replace(/^\./, "").toLowerCase() === ext)) {
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
return assetExts.has(ext);
|
|
205
|
+
}
|
|
206
|
+
|
|
188
207
|
export function resolveRelativePlatformFile(request, fromFile, platform, sourceExts) {
|
|
189
208
|
const base = path.resolve(path.dirname(fromFile), request);
|
|
190
209
|
return resolvePlatformFile(
|
package/dist/presets.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as navigation, a as keyboardController, b as reanimated, c as vectorIcons, d as netInfo, f as mmkv, g as asyncStorage, h as screens, i as worklets, l as webview, m as expo, n as skia, o as bottomSheet, p as deviceInfo, r as unistyles, s as flashList, u as svg, v as safeAreaContext, y as gestureHandler } from "./index-
|
|
1
|
+
import { _ as navigation, a as keyboardController, b as reanimated, c as vectorIcons, d as netInfo, f as mmkv, g as asyncStorage, h as screens, i as worklets, l as webview, m as expo, n as skia, o as bottomSheet, p as deviceInfo, r as unistyles, s as flashList, u as svg, v as safeAreaContext, y as gestureHandler } from "./index-aNBCTfA5.mjs";
|
|
2
2
|
export { asyncStorage, bottomSheet, deviceInfo, expo, flashList, gestureHandler, keyboardController, mmkv, navigation, netInfo, reanimated, safeAreaContext, screens, skia, svg, unistyles, vectorIcons, webview, worklets };
|
|
@@ -82,9 +82,11 @@ other APIs as described in its migration guide.
|
|
|
82
82
|
You do **not** need `jest.mock('react-native-reanimated', …)`, safe-area's `jest/mock`,
|
|
83
83
|
gesture-handler's jestSetup, etc. vitest-native **auto-detects** installed third-party libraries and
|
|
84
84
|
shadows their native runtimes with built-in presets, under **both** engines. Just have the package
|
|
85
|
-
installed; delete the manual mock. (Reanimated, Gesture Handler, Safe Area, Navigation, Screens
|
|
86
|
-
AsyncStorage
|
|
87
|
-
`tests-native/third-party-stack.test.tsx`.
|
|
85
|
+
installed; delete the manual mock. (Reanimated, Gesture Handler, Safe Area, Navigation, Screens and
|
|
86
|
+
AsyncStorage are covered out of the box. Validated under the native engine —
|
|
87
|
+
`tests-native/third-party-stack.test.tsx`. Expo modules need no mock either: under the native engine
|
|
88
|
+
they run their own JavaScript, as under jest-expo, and the `expo` preset applies only under the mock
|
|
89
|
+
engine, or when you turn it on with `presets: { expo: true }` or list it in a `presets` array.)
|
|
88
90
|
|
|
89
91
|
### 2d. Snapshots: keep Jest's and Vitest's apart, then record Vitest's
|
|
90
92
|
Jest's `.snap` files are not something Vitest can check against, for two reasons.
|
|
@@ -225,7 +227,7 @@ see the [Expo guide](https://danfry1.github.io/vitest-native/guide/expo).
|
|
|
225
227
|
5. Triage remaining failures — a missing query update, a suite-specific mock, or a known
|
|
226
228
|
Jest-mock-coupled assertion (section 3). For runtime issues (large-suite memory limits,
|
|
227
229
|
error-boundary console noise, overriding a preset's mock), see the
|
|
228
|
-
[
|
|
230
|
+
[troubleshooting guide](https://danfry1.github.io/vitest-native/guide/troubleshooting).
|
|
229
231
|
|
|
230
232
|
## 5. What "done" looks like
|
|
231
233
|
|