vitest-native 0.15.0 → 0.15.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/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { A as PEER_REQUIREMENTS, C as SUPPORTED_NODE, E as unsupportedNodeMessage, F as unsupportedExpoSdkMessage, I as unsupportedReactNativeMessage, M as belowRecommendedMessage, N as installedExpoVersion, O as validatePeerDependency, P as isBelowSupportedReactNative, T as satisfiesNodeRange, _ as isKnownPlugin, c as detectEcosystemPackages, d as detectEngine, g as classifyBabelPlugins, h as projectBabelTrigger, i as ownVitestPackage, l as babelParser, m as missingBabelCoreNotice, o as usesVitePlus, r as installedViteVersion, u as isPlainJavaScript, v as normalizeBabelName, y as installedManifest } from "./host-TAGjG56H.mjs";
3
- import { a as PRESET_MODULES, f as presetShadowing, i as LIBRARY_SETUP_FILES, m as testsItself, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
2
+ import { A as PEER_REQUIREMENTS, C as SUPPORTED_NODE, E as unsupportedNodeMessage, F as unsupportedExpoSdkMessage, I as unsupportedReactNativeMessage, M as belowRecommendedMessage, N as installedExpoVersion, O as validatePeerDependency, P as isBelowSupportedReactNative, T as satisfiesNodeRange, _ as isKnownPlugin, c as detectEcosystemPackages, d as detectEngine, g as classifyBabelPlugins, h as projectBabelTrigger, i as ownVitestPackage, l as babelParser, m as missingBabelCoreNotice, o as usesVitePlus, r as installedViteVersion, u as isPlainJavaScript, v as normalizeBabelName, y as installedManifest } from "./host-BY3RaLPW.mjs";
3
+ import { a as PRESET_MODULES, f as presetShadowing, i as LIBRARY_SETUP_FILES, l as libraryMockUsable, m as testsItself, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
4
4
  import { n as ignorePattern, t as findNodeModuleMocks } from "./root-mocks-DP95ncxD.mjs";
5
5
  import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-Couw0Esx.mjs";
6
6
  import { createRequire } from "node:module";
@@ -1010,13 +1010,20 @@ function extractAllowlistPackages(pattern) {
1010
1010
  };
1011
1011
  const entries = [];
1012
1012
  const unparseable = [];
1013
+ const written = body.replace(/\\(.)/g, "$1");
1013
1014
  for (const alternative of topLevelAlternatives(body)) {
1014
1015
  const classified = tryExpand(alternative, true)?.filter((e) => !e.startsWith(".")).map(classify$1);
1015
1016
  if (!classified || classified.some((c) => c === null)) {
1016
1017
  unparseable.push(alternative);
1017
1018
  continue;
1018
1019
  }
1019
- for (const entry of classified) if (!entries.some((e) => e.name === entry.name && e.kind === entry.kind)) entries.push(entry);
1020
+ for (const entry of classified) {
1021
+ if (entries.some((e) => e.name === entry.name && e.kind === entry.kind)) continue;
1022
+ entries.push(written.includes(entry.name) ? entry : {
1023
+ ...entry,
1024
+ expanded: true
1025
+ });
1026
+ }
1020
1027
  }
1021
1028
  return {
1022
1029
  entries,
@@ -1728,9 +1735,12 @@ function mockFactoryForwardReads(root) {
1728
1735
  * - A snapshot serializer that only strips `jestAnimatedProps`, `jestAnimatedStyle` and
1729
1736
  * `jestInlineStyle`: Reanimated's real AnimatedComponent adds those props under Jest;
1730
1737
  * its mock's createAnimatedComponent and the preset's module add none.
1731
- * - A setup file that only calls `setUpTests()`: vitest-native registers
1732
- * toHaveAnimatedStyle and toHaveAnimatedProps itself, and Reanimated's own versions read
1733
- * props its mock does not set (presets/reanimated.ts keeps the engine's).
1738
+ * - A setup file that only calls `setUpTests()`, in a suite that also mocks Reanimated:
1739
+ * vitest-native registers toHaveAnimatedStyle and toHaveAnimatedProps itself, and
1740
+ * Reanimated's own versions read props its mock does not set (presets/reanimated.ts
1741
+ * keeps the engine's). A suite that calls `setUpTests()` and mocks Reanimated nowhere
1742
+ * ran the real library: migrate turns the preset off for it instead and keeps the file
1743
+ * (callsReanimatedSetUpTests, #834).
1734
1744
  */
1735
1745
  const RESOLVER = /(?:^|node_modules\/)(react-native-(?:reanimated|worklets))\/jest\/resolver(?:\.js)?$/;
1736
1746
  /** The library whose own Jest resolver `resolver` names, or null. */
@@ -1801,6 +1811,25 @@ function onlyCallsSetUpTests(source) {
1801
1811
  const statements = code.split(/[;\n]/).map((s) => s.trim()).filter(Boolean);
1802
1812
  return statements.filter((s) => /setUpTests\(\s*\)$/.test(s)).length === 1 && statements.every((s) => SETUP_STATEMENTS.some((re) => re.test(s)));
1803
1813
  }
1814
+ /**
1815
+ * Whether a setup file runs Reanimated's `setUpTests()`: it takes `setUpTests` from
1816
+ * `react-native-reanimated` and calls it, with or without arguments. Whole-line comments
1817
+ * are ignored; a file that cannot be read exactly does not count.
1818
+ */
1819
+ function callsReanimatedSetUpTests(source) {
1820
+ const code = withoutComments(source);
1821
+ if (code === null) return false;
1822
+ return /require\(\s*['"]react-native-reanimated['"]\s*\)\.setUpTests\(/.test(code) || /\{[^}]*\bsetUpTests\b[^}]*\}\s*(?:=\s*require\(\s*['"]react-native-reanimated['"]\s*\)|from\s*['"]react-native-reanimated['"])/.test(code) && /(?:^|[^.\w])setUpTests\s*\(/m.test(code);
1823
+ }
1824
+ /**
1825
+ * Whether a setup file mocks Reanimated itself (`jest.mock('react-native-reanimated', …)`),
1826
+ * so the suite runs its mock, not the library. A commented-out mock does not count; a file
1827
+ * that cannot be read exactly does, which keeps the mock, as before.
1828
+ */
1829
+ function mocksReanimated(source) {
1830
+ const code = withoutComments(source);
1831
+ return code === null || /\bjest\.mock\(\s*(['"])react-native-reanimated\1/.test(code);
1832
+ }
1804
1833
  // src/cli/untranspiled.ts
1805
1834
  /**
1806
1835
  * Evidence that a package needs `transform`: a `.js` file under one of its entry
@@ -2123,17 +2152,7 @@ function analyzeJestConfig(root) {
2123
2152
  const presetKeys = Object.keys(resolvedPreset?.own ?? {});
2124
2153
  const config = projectConfig && resolvedPreset && presetKeys.length ? withPresetSettings(projectConfig, resolvedPreset.own) : projectConfig;
2125
2154
  const jestPreset = resolvedPreset?.name;
2126
- const navigationOff = /^jest-expo(\/(ios|android|universal))?$/.test(jestPreset ?? "") && activePresets(root).includes("navigation") && !fs.existsSync(path.join(root, "__mocks__", "@react-navigation"));
2127
- const active = activePresets(root, navigationOff ? ["navigation"] : []);
2128
- const runsWithOwnSetup = (preset) => LIBRARY_SETUP_FILES[preset] !== void 0 && !active.includes(preset);
2129
- const autoInlined = new Set(detectEcosystemPackages(root, [], [], [], active));
2130
- const addAlias = (key, value) => {
2131
- if (aliasKeys.has(key)) return false;
2132
- aliasKeys.add(key);
2133
- aliasEntries.push(`${JSON.stringify(key)}: ${value}`);
2134
- aliasArray.push(`{ find: ${JSON.stringify(key)}, replacement: ${value} }`);
2135
- return true;
2136
- };
2155
+ const fromJestExpo = /^jest-expo(\/(ios|android|universal))?$/.test(jestPreset ?? "");
2137
2156
  const projectSource = (file) => {
2138
2157
  if (/^(?:<rootDir>\/|\.\/)?node_modules\//.test(file)) return null;
2139
2158
  const rel = file.replace(/^<rootDir>\/?/, "");
@@ -2145,6 +2164,67 @@ function analyzeJestConfig(root) {
2145
2164
  ].find((candidate) => fs.statSync(candidate, { throwIfNoEntry: false })?.isFile());
2146
2165
  return found === void 0 ? null : fs.readFileSync(found, "utf8");
2147
2166
  };
2167
+ const setupSources = ["setupFiles", "setupFilesAfterEnv"].flatMap((key) => Array.isArray(config?.[key]) ? config[key] : []).filter((f) => typeof f === "string").map((f) => ({
2168
+ file: f,
2169
+ code: projectSource(f)
2170
+ })).filter((f) => f.code !== null);
2171
+ const realReanimatedSetup = setupSources.find(({ code }) => callsReanimatedSetUpTests(code));
2172
+ const reanimatedMocked = setupSources.some(({ code }) => mocksReanimated(code)) || [
2173
+ "",
2174
+ ".js",
2175
+ ".ts",
2176
+ ".tsx"
2177
+ ].some((ext) => fs.existsSync(path.join(root, "__mocks__", `react-native-reanimated${ext}`))) || Object.keys(config?.moduleNameMapper ?? {}).some((pattern) => {
2178
+ try {
2179
+ return new RegExp(pattern).test("react-native-reanimated");
2180
+ } catch {
2181
+ return false;
2182
+ }
2183
+ });
2184
+ const ranRealReanimated = realReanimatedSetup !== void 0 && !reanimatedMocked && activePresets(root).includes("reanimated") && libraryMockUsable(root);
2185
+ const reanimatedReal = ranRealReanimated && declaredDependencies(root).includes("react-native-reanimated");
2186
+ const navigationOff = fromJestExpo && activePresets(root).includes("navigation") && !fs.existsSync(path.join(root, "__mocks__", "@react-navigation"));
2187
+ const presetsOff = [...navigationOff ? ["navigation"] : [], ...reanimatedReal ? ["reanimated"] : []];
2188
+ const active = activePresets(root, presetsOff);
2189
+ const runsWithOwnSetup = (preset) => LIBRARY_SETUP_FILES[preset] !== void 0 && !active.includes(preset);
2190
+ const autoInlined = new Set(detectEcosystemPackages(root, [], [], [], active));
2191
+ const addAlias = (key, value) => {
2192
+ if (aliasKeys.has(key)) return false;
2193
+ aliasKeys.add(key);
2194
+ aliasEntries.push(`${JSON.stringify(key)}: ${value}`);
2195
+ aliasArray.push(`{ find: ${JSON.stringify(key)}, replacement: ${value} }`);
2196
+ return true;
2197
+ };
2198
+ const scannedSetupFiles = /* @__PURE__ */ new Set();
2199
+ let parseSetup;
2200
+ const coveredSetupLines = (file) => {
2201
+ const resolved = path.resolve(root, file.replace(/^<rootDir>\/?/, ""));
2202
+ if (scannedSetupFiles.has(resolved)) return [];
2203
+ scannedSetupFiles.add(resolved);
2204
+ const code = projectSource(file);
2205
+ if (code === null) return [];
2206
+ parseSetup ??= babelParser(root);
2207
+ const statements = parseSetup ? setupStatements(parseSetup, code) : [];
2208
+ const lines = [];
2209
+ for (const { mocked, request, imported, factory } of statements) {
2210
+ const pkg = /^(@[^/]+\/[^/]+|[^@./][^/]*)/.exec(mocked ?? request ?? "")?.[1];
2211
+ const preset = mocked !== void 0 ? presetShadowing(mocked) : pkg && presetShadowing(pkg);
2212
+ if (!pkg || !preset) continue;
2213
+ if (!active.includes(preset) && !runsWithOwnSetup(preset)) continue;
2214
+ const shown = mocked ? `jest.mock('${mocked}')` : imported ? `import '${request}'` : `require('${request}')`;
2215
+ if (factory && keepsPartOfModule(factory)) {
2216
+ attention.push(`${file}: ${shown} — the ${preset} preset provides ${pkg}, but this mock changes part of it (jest.requireActual or a spread); keep only the changes the tests rely on.`);
2217
+ continue;
2218
+ }
2219
+ const ownSetup = LIBRARY_SETUP_FILES[preset];
2220
+ if (active.includes(preset)) lines.push(`${file}: ${shown} — the auto-detected ${preset} preset shadows ${pkg}; delete the line.`);
2221
+ else {
2222
+ const isOwnSetup = request !== void 0 && request.replace(/\.js$/, "") === ownSetup?.replace(/\.js$/, "");
2223
+ lines.push(isOwnSetup ? `${file}: ${shown} — ${pkg}'s own test setup, which the native engine runs before the setup files; delete the line.` : `${file}: ${shown} — the native engine runs ${pkg} with its own Jest setup (${ownSetup}), which replaces its native layer; delete the line.`);
2224
+ }
2225
+ }
2226
+ return lines;
2227
+ };
2148
2228
  const reanimatedActive = active.includes("reanimated");
2149
2229
  const absolutePath = (relative) => {
2150
2230
  needsUrlImport = true;
@@ -2182,14 +2262,16 @@ function analyzeJestConfig(root) {
2182
2262
  if (/react-native\/jest\/setup/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
2183
2263
  else if (setupPreset && active.includes(setupPreset)) presetCovered.push(`${key}: '${f}' — ${setupPackage}'s own test setup; the auto-detected ${setupPreset} preset shadows ${setupPackage}, and this file's jest.mock() calls would replace it; delete.`);
2184
2264
  else if (setupPreset && runsWithOwnSetup(setupPreset) && asRequest.replace(/\.js$/, "") === LIBRARY_SETUP_FILES[setupPreset]?.replace(/\.js$/, "")) presetCovered.push(`${key}: '${f}' — ${setupPackage}'s own test setup, which the native engine runs before the setup files (${LIBRARY_SETUP_FILES[setupPreset]}); delete.`);
2185
- else if (reanimatedActive && onlyCallsSetUpTests(projectSource(f) ?? "")) presetCovered.push(`${key}: '${f}' — only calls Reanimated's setUpTests(), whose matchers cannot see the rendered style here; vitest-native registers toHaveAnimatedStyle and toHaveAnimatedProps itself; delete.`);
2265
+ else if (reanimatedActive && !ranRealReanimated && onlyCallsSetUpTests(projectSource(f) ?? "")) presetCovered.push(`${key}: '${f}' — only calls Reanimated's setUpTests(), whose matchers cannot see the rendered style here; vitest-native registers toHaveAnimatedStyle and toHaveAnimatedProps itself; delete.`);
2186
2266
  else if (/jest-expo/.test(f)) attention.push(`${key}: '${f}' — ${expoPresetCoverage()}.`);
2187
2267
  else if (f.startsWith("<rootDir>")) {
2188
2268
  setupFiles.push(absolutePath(f.replace(/^<rootDir>\/?/, "./")));
2189
2269
  automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
2270
+ presetCovered.push(...coveredSetupLines(f));
2190
2271
  } else {
2191
2272
  setupFiles.push(JSON.stringify(f));
2192
2273
  automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
2274
+ presetCovered.push(...coveredSetupLines(f));
2193
2275
  }
2194
2276
  }
2195
2277
  }
@@ -2242,7 +2324,6 @@ function analyzeJestConfig(root) {
2242
2324
  if (entries.length === 0 && unparseable.length === 0) attention.push(`transformIgnorePatterns: ${JSON.stringify(tip)} — could not extract an allowlist automatically; packages shipping untranspiled source go in reactNative({ transform: [...] }).`);
2243
2325
  else classifyAllowlist(root, entries, active, autoInlined, {
2244
2326
  automatic,
2245
- presetCovered,
2246
2327
  transformPkgs
2247
2328
  });
2248
2329
  }
@@ -2409,10 +2490,10 @@ function analyzeJestConfig(root) {
2409
2490
  for (const duplicate of manualMocks.duplicates) attention.push(`duplicate manual mock ${duplicate.name}: ${duplicate.files.map(relative).join(", ")} — Jest warns and uses one; jestMockTransform() uses the last listed. Delete the others.`);
2410
2491
  const transformOptions = [...jestRoots && jestRoots.some((r) => r !== ".") ? [`roots: [${jestRoots.map((r) => JSON.stringify(r)).join(", ")}]`] : [], ...manualMocks.mocks.length > 0 && jestIgnorePatterns?.length ? [`modulePathIgnorePatterns: [${jestIgnorePatterns.map((p) => JSON.stringify(p)).join(", ")}]`] : []];
2411
2492
  const transformCall = transformOptions.length ? `jestMockTransform({ ${transformOptions.join(", ")} })` : "jestMockTransform()";
2412
- if (navigationOff) {
2413
- pluginOptions.push(`presets: { navigation: false }`);
2414
- automatic.push("jest-expo renders the real React Navigation → presets: { navigation: false }, so screens keep running in real navigators.");
2415
- }
2493
+ if (presetsOff.length) pluginOptions.push(`presets: { ${presetsOff.map((p) => `${p}: false`).join(", ")} }`);
2494
+ if (ranRealReanimated && !reanimatedReal) attention.push(`${realReanimatedSetup.file} runs Reanimated's setUpTests() and the suite mocks Reanimated nowhere, so under Jest it ran the real library; here the reanimated preset serves its mock. To run the real library, declare react-native-reanimated in package.json and add presets: { reanimated: false }.`);
2495
+ if (reanimatedReal) automatic.push(`${realReanimatedSetup.file} runs Reanimated's setUpTests() and the suite mocks Reanimated nowhere: it ran the real library under Jest → presets: { reanimated: false }, so Reanimated runs as itself (through its own Jest resolver), and the setup file stays.`);
2496
+ if (navigationOff) automatic.push("jest-expo renders the real React Navigation → presets: { navigation: false }, so screens keep running in real navigators.");
2416
2497
  const factoryReads = mockFactoryForwardReads(root);
2417
2498
  if (factoryReads.length) {
2418
2499
  const shown = factoryReads.slice(0, 5).map((r) => `${r.file}:${r.line} (jest.mock('${r.module}') reads ${r.names.join(", ")})`);
@@ -2506,6 +2587,64 @@ export default defineConfig({
2506
2587
  ok: source !== null
2507
2588
  };
2508
2589
  }
2590
+ const isAstNode = (v) => !!v && typeof v === "object" && typeof v.type === "string";
2591
+ const stringValue = (n) => isAstNode(n) && n.type === "StringLiteral" ? n.value : void 0;
2592
+ /**
2593
+ * A setup file's top-level `jest.mock('<id>', …)`, `require('<id>')` and `import '<id>'`
2594
+ * statements. Nothing when the file does not parse.
2595
+ */
2596
+ function setupStatements(parse, code) {
2597
+ let ast;
2598
+ try {
2599
+ ast = parse(code, {
2600
+ sourceType: "unambiguous",
2601
+ plugins: ["typescript", "jsx"],
2602
+ allowReturnOutsideFunction: true,
2603
+ allowAwaitOutsideFunction: true
2604
+ });
2605
+ } catch {
2606
+ return [];
2607
+ }
2608
+ return (ast.program?.body ?? []).flatMap((statement) => {
2609
+ if (statement.type === "ImportDeclaration") {
2610
+ const request = stringValue(statement.source);
2611
+ const named = statement.specifiers?.length ?? 0;
2612
+ return request !== void 0 && named === 0 ? [{
2613
+ request,
2614
+ imported: true
2615
+ }] : [];
2616
+ }
2617
+ if (statement.type !== "ExpressionStatement") return [];
2618
+ const call = statement.expression;
2619
+ if (!isAstNode(call) || call.type !== "CallExpression") return [];
2620
+ const callee = call.callee;
2621
+ const args = call.arguments;
2622
+ const id = stringValue(args[0]);
2623
+ if (id === void 0) return [];
2624
+ if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.object.name === "jest" && callee.property.name === "mock") return [{
2625
+ mocked: id,
2626
+ factory: args[1]
2627
+ }];
2628
+ if (callee.type === "Identifier" && callee.name === "require" && args.length === 1) return [{ request: id }];
2629
+ return [];
2630
+ });
2631
+ }
2632
+ /** Whether a mock factory keeps part of the real module: `jest.requireActual`, a spread. */
2633
+ function keepsPartOfModule(node) {
2634
+ if (Array.isArray(node)) return node.some(keepsPartOfModule);
2635
+ if (!isAstNode(node)) return false;
2636
+ if (node.type === "SpreadElement") return true;
2637
+ if (node.type === "MemberExpression" && !node.computed && node.property.name === "requireActual") return true;
2638
+ return Object.entries(node).some(([key, value]) => ![
2639
+ "loc",
2640
+ "start",
2641
+ "end",
2642
+ "leadingComments",
2643
+ "trailingComments",
2644
+ "innerComments",
2645
+ "extra"
2646
+ ].includes(key) && typeof value === "object" && keepsPartOfModule(value));
2647
+ }
2509
2648
  /**
2510
2649
  * What each package a transformIgnorePatterns allowlist lets through needs here.
2511
2650
  * Jest compiles nothing in node_modules unless allowed, so its allowlists mix React
@@ -2517,7 +2656,9 @@ export default defineConfig({
2517
2656
  * Prefix and scope entries are matched against the project's declared dependencies.
2518
2657
  */
2519
2658
  function classifyAllowlist(root, entries, active, autoInlined, out) {
2520
- const candidates = /* @__PURE__ */ new Set([...declaredDependencies(root), ...entries.filter((e) => e.kind === "exact").map((e) => e.name)]);
2659
+ const declared = new Set(declaredDependencies(root));
2660
+ const candidates = /* @__PURE__ */ new Set([...declared, ...entries.filter((e) => e.kind === "exact").map((e) => e.name)]);
2661
+ const spelled = new Set(entries.filter((e) => e.kind === "exact" && !e.expanded).map((e) => e.name));
2521
2662
  const groups = {
2522
2663
  rn: [],
2523
2664
  detected: [],
@@ -2530,8 +2671,9 @@ function classifyAllowlist(root, entries, active, autoInlined, out) {
2530
2671
  if (pkg === "react-native" || pkg.startsWith("@react-native/")) groups.rn.push(pkg);
2531
2672
  else if (preset && active.includes(preset)) shadowed.set(preset, [...shadowed.get(preset) ?? [], pkg]);
2532
2673
  else if (autoInlined.has(pkg)) groups.detected.push(pkg);
2533
- else if (!installedManifest(root, pkg)) groups.absent.push(pkg);
2534
- else {
2674
+ else if (!installedManifest(root, pkg)) {
2675
+ if (declared.has(pkg) || spelled.has(pkg)) groups.absent.push(pkg);
2676
+ } else {
2535
2677
  const evidence = untranspiledFile(root, pkg);
2536
2678
  if (evidence) {
2537
2679
  out.transformPkgs.push(pkg);
@@ -2540,7 +2682,7 @@ function classifyAllowlist(root, entries, active, autoInlined, out) {
2540
2682
  }
2541
2683
  }
2542
2684
  if (groups.rn.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.rn)} — the native engine transforms React Native itself; nothing to do.`);
2543
- for (const [preset, pkgs] of shadowed) out.presetCovered.push(`transformIgnorePatterns allows ${list(pkgs)} — shadowed by the auto-detected ${preset} preset; nothing to do.`);
2685
+ for (const [preset, pkgs] of shadowed) out.automatic.push(`transformIgnorePatterns allows ${list(pkgs)} — shadowed by the auto-detected ${preset} preset; nothing to do.`);
2544
2686
  if (groups.detected.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.detected)} — detected by the engine (React Native ecosystem), which compiles what Node cannot run; nothing to do.`);
2545
2687
  if (groups.absent.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.absent)} — not installed; nothing to do.`);
2546
2688
  }
package/dist/errors.d.mts CHANGED
@@ -51,12 +51,14 @@ export type VitestNativeErrorCode =
51
51
  | "PROJECT_BABEL_COMMONJS"
52
52
  | "PRESET_UNAVAILABLE"
53
53
  | "PRESET_NOT_PREPARED"
54
+ | "PRESET_REACT_MISMATCH"
54
55
  | "WRONG_ENGINE_FOR_HELPER"
55
56
  | "HELPERS_BEFORE_SETUP"
56
57
  | "JEST_API_UNSUPPORTED"
57
58
  | "REQUIRE_ACTUAL_ALIAS_UNSUPPORTED"
58
59
  | "JEST_MOCK_FACTORY_CYCLE"
59
60
  | "JEST_COMPAT_SETUP_MISSING"
61
+ | "JEST_BINDING_NOT_FOLLOWED"
60
62
  | "BABEL_IGNORES_FILE"
61
63
  | "LIBRARY_REGISTRY_FAILED"
62
64
  | "UNKNOWN_DISPATCH_STEP"
@@ -34,6 +34,8 @@ export declare class HangWatch {
34
34
  now?: () => number;
35
35
  cli?: boolean;
36
36
  graceMs?: number;
37
+ /** Measures time the machine spends asleep (native/suspension.mjs); a test seam. */
38
+ suspension?: { tick(): void; readonly suspendedMs: number };
37
39
  });
38
40
  timeoutMs: number | null;
39
41
  readonly recordsDir: string | undefined;
@@ -20,6 +20,7 @@
20
20
  import { spawnSync } from "node:child_process";
21
21
  import fs from "node:fs";
22
22
  import path from "node:path";
23
+ import { suspensionTracker } from "./native/suspension.mjs";
23
24
 
24
25
  /** The default no-progress limit when `hangTimeout` is not set. */
25
26
  export const DEFAULT_HANG_TIMEOUT = 60_000;
@@ -170,6 +171,9 @@ export function runByCli(argv = process.argv) {
170
171
  return /(^|[\\/])vitest(\.m?js)?$/.test(argv[1] ?? "");
171
172
  }
172
173
 
174
+ /** How often the watch reads the suspension tracker while files are in flight. */
175
+ const SUSPENSION_POLL_MS = 1000;
176
+
173
177
  export class HangWatch {
174
178
  constructor({
175
179
  timeoutMs,
@@ -181,6 +185,10 @@ export class HangWatch {
181
185
  now = () => Date.now(),
182
186
  cli = runByCli(),
183
187
  graceMs = 5000,
188
+ // Time the machine spends asleep is not progress, and not a hang either (#689): a
189
+ // sleep mid-run read as every running test past its budget, and stopped the run on
190
+ // wake. Measured, since Node's clocks count sleep on macOS (native/suspension.mjs).
191
+ suspension = suspensionTracker({ intervalMs: SUSPENSION_POLL_MS }),
184
192
  }) {
185
193
  this.timeoutMs = timeoutMs ?? null;
186
194
  this.recordsDir = recordsDir;
@@ -204,6 +212,14 @@ export class HangWatch {
204
212
  * none.
205
213
  */
206
214
  this.lastActivity = 0;
215
+ /** When the last progress restarted the limit. */
216
+ this.progressAt = 0;
217
+ this.suspension = suspension;
218
+ /** The tracker's total time asleep when the watch last read it. */
219
+ this.seenSuspendedMs = suspension.suspendedMs;
220
+ /** Each suspension seen during the run: when it was noticed (`now`), and how long. */
221
+ this.suspensions = [];
222
+ this.poller = undefined;
207
223
  this.timer = undefined;
208
224
  this.vitest = undefined;
209
225
  }
@@ -232,7 +248,10 @@ export class HangWatch {
232
248
  onTestRunStart() {
233
249
  this.running.clear();
234
250
  this.takenAt.clear();
251
+ this.seenSuspendedMs = this.suspension.suspendedMs;
252
+ this.suspensions = [];
235
253
  this.disarm();
254
+ this.stopPolling();
236
255
  }
237
256
 
238
257
  /** Called by the plugin for each module the main process transforms (see lastActivity). */
@@ -280,15 +299,47 @@ export class HangWatch {
280
299
  this.running.clear();
281
300
  this.takenAt.clear();
282
301
  this.disarm();
302
+ this.stopPolling();
283
303
  }
284
304
 
285
305
  /** Restart the limit while any file is in flight; otherwise stop watching. */
286
306
  progress() {
287
307
  this.disarm();
288
308
  if (!this.watching() || this.running.size === 0) return;
309
+ this.progressAt = this.now();
310
+ this.startPolling();
289
311
  this.arm(this.timeoutMs);
290
312
  }
291
313
 
314
+ /** Read the suspension tracker, recording any new time asleep. */
315
+ pollSuspensions() {
316
+ // Measured from the last reading, not from just before this tick: the tracker can
317
+ // record a sleep between polls (its own timer, or a tick from elsewhere), and a
318
+ // before/after pair around this tick would never see it.
319
+ this.suspension.tick();
320
+ const slept = this.suspension.suspendedMs - this.seenSuspendedMs;
321
+ this.seenSuspendedMs = this.suspension.suspendedMs;
322
+ if (slept > 0) this.suspensions.push({ at: this.now(), ms: slept });
323
+ }
324
+
325
+ /** Time asleep noticed after `since` (a `now` reading). */
326
+ asleepSince(since) {
327
+ let ms = 0;
328
+ for (const s of this.suspensions) if (s.at > since) ms += s.ms;
329
+ return ms;
330
+ }
331
+
332
+ startPolling() {
333
+ if (this.poller) return;
334
+ this.poller = setInterval(() => this.pollSuspensions(), SUSPENSION_POLL_MS);
335
+ this.poller.unref?.();
336
+ }
337
+
338
+ stopPolling() {
339
+ clearInterval(this.poller);
340
+ this.poller = undefined;
341
+ }
342
+
292
343
  arm(ms) {
293
344
  this.disarm();
294
345
  this.timer = setTimeout(() => this.check(), ms);
@@ -301,16 +352,22 @@ export class HangWatch {
301
352
  * until that budget runs out; otherwise the run is stuck.
302
353
  */
303
354
  check() {
355
+ // A check that fires on wake sees the sleep that just ended. Every budget below moves
356
+ // on by the time asleep since it started.
357
+ this.pollSuspensions();
304
358
  const records = readTestRecords(this.recordsDir);
305
- let waitUntil = 0;
359
+ let waitUntil = this.progressAt + this.timeoutMs + this.asleepSince(this.progressAt);
306
360
  for (const file of this.running.keys()) {
307
361
  const record = records.get(file);
308
362
  if (!record) continue;
309
363
  if (record.debugger) return this.arm(this.timeoutMs);
310
- waitUntil = Math.max(waitUntil, record.at + testBudget(record));
364
+ waitUntil = Math.max(waitUntil, record.at + testBudget(record) + this.asleepSince(record.at));
311
365
  }
312
366
  // Modules still loading somewhere in the run: progress the events cannot show.
313
- if (this.lastActivity > 0) waitUntil = Math.max(waitUntil, this.lastActivity + this.timeoutMs);
367
+ if (this.lastActivity > 0) {
368
+ const since = this.lastActivity;
369
+ waitUntil = Math.max(waitUntil, since + this.timeoutMs + this.asleepSince(since));
370
+ }
314
371
  const left = waitUntil - this.now();
315
372
  if (left > 0) return this.arm(left);
316
373
  this.trip(records);
@@ -595,7 +595,7 @@ const KNOWN_PLUGINS = [
595
595
  {
596
596
  names: ["babel-plugin-react-compiler"],
597
597
  verdict: "unneeded",
598
- reason: () => "React Compiler only adds memoization to components that follow the Rules of React (react.dev/learn/react-compiler); they render the same without it."
598
+ reason: () => "tests run without it. It applies to the files projectBabel compiles with Babel ('auto': those another entry needs; 'always': all). There a memoized child given the same props skips re-rendering, so a test reading a value React does not track during render (a shared value, a ref) can see it keep its earlier value. Other files run without it, so a test that counts renders can see more than under babel-jest."
599
599
  }
600
600
  ];
601
601
  const unknownReason = (e) => `${e.written} ran on every file under babel-jest and does not run under vitest-native; check whether tests depend on what it does.`;
@@ -193,9 +193,23 @@ interface ReactNativeMock {
193
193
  usePressability: Mock;
194
194
  default: ReactNativeMock;
195
195
  }
196
+ /** What a preset module's factory is given when it builds its mock. */
197
+ interface PresetFactoryContext {
198
+ /**
199
+ * The React the test file renders with: the copy `react-native` resolves (the
200
+ * project's, where `react-native` is not installed). A mock that creates components,
201
+ * contexts or hooks uses this one rather than a React it imported itself: under the
202
+ * hot runtime's `freshRuntime` each file has its own React, and a hook or context from
203
+ * another file's React fails there.
204
+ */
205
+ React: typeof import("react");
206
+ }
196
207
  interface PresetModule {
197
- /** Factory that builds the mock object. Only called in Vitest worker processes. */
198
- factory: () => Record<string, any>;
208
+ /**
209
+ * Factory that builds the mock object, once per test file that imports the module.
210
+ * Only called in Vitest worker processes.
211
+ */
212
+ factory: (context: PresetFactoryContext) => Record<string, any>;
199
213
  /** Static list of named exports for virtual ESM module generation. Read at Vite config time (no vitest available). */
200
214
  exports: string[];
201
215
  /**
@@ -572,4 +586,4 @@ declare function skia(): Preset;
572
586
  declare namespace index_d_exports {
573
587
  export { asyncStorage, bottomSheet, deviceInfo, expo, flashList, gestureHandler, keyboardController, mmkv, navigation, netInfo, reanimated, safeAreaContext, screens, skia, svg, unistyles, vectorIcons, webview, worklets };
574
588
  }
575
- export { VitestNativeOptions as C, ReactNativeMock as S, navigation as _, keyboardController as a, reanimated as b, vectorIcons as c, netInfo as d, mmkv as f, asyncStorage as g, screens as h, worklets as i, webview as l, expo as m, skia as n, bottomSheet as o, deviceInfo as p, unistyles as r, flashList as s, index_d_exports as t, svg as u, safeAreaContext as v, Preset as x, gestureHandler as y };
589
+ export { ReactNativeMock as C, PresetFactoryContext as S, navigation as _, keyboardController as a, reanimated as b, vectorIcons as c, netInfo as d, mmkv as f, asyncStorage as g, screens as h, worklets as i, webview as l, expo as m, skia as n, bottomSheet as o, deviceInfo as p, unistyles as r, flashList as s, index_d_exports as t, svg as u, safeAreaContext as v, VitestNativeOptions as w, Preset as x, gestureHandler as y };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { C as VitestNativeOptions, S as ReactNativeMock, t as index_d_exports, x as Preset } from "./index-BpZ0E2eJ.mjs";
2
- import "./context.mjs";
1
+ import { C as ReactNativeMock, S as PresetFactoryContext, t as index_d_exports, w as VitestNativeOptions, x as Preset } from "./index-DQz6guT5.mjs";
3
2
  import { Plugin } from "vite";
3
+ import "./context.mjs";
4
4
  /**
5
5
  * Preset names switched off by the object form of the `presets` option.
6
6
  *
@@ -11,4 +11,4 @@ import { Plugin } from "vite";
11
11
  */
12
12
  export declare function disabledPresetNames(presets: unknown): Set<string>;
13
13
  export declare function reactNative(options?: VitestNativeOptions): Plugin;
14
- export { type Preset, type ReactNativeMock, type VitestNativeOptions, index_d_exports as presets };
14
+ export { type Preset, type PresetFactoryContext, type ReactNativeMock, type VitestNativeOptions, index_d_exports as presets };