vitest-native 0.15.0 → 0.16.0-rc.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.
Files changed (54) hide show
  1. package/dist/cli.mjs +177 -31
  2. package/dist/context.d.mts +6 -0
  3. package/dist/context.mjs +5 -0
  4. package/dist/errors.d.mts +5 -0
  5. package/dist/hang-watch.d.mts +2 -0
  6. package/dist/hang-watch.mjs +60 -3
  7. package/dist/{host-TAGjG56H.mjs → host-X6VHF-a4.mjs} +456 -15
  8. package/dist/{index-BpZ0E2eJ.d.mts → index-X3wuvaqa.d.mts} +25 -13
  9. package/dist/index.d.mts +3 -3
  10. package/dist/index.mjs +220 -117
  11. package/dist/jest-compat/jest-object.mjs +62 -17
  12. package/dist/jest-compat/node-registry.mjs +496 -126
  13. package/dist/jest-compat/setup.mjs +32 -4
  14. package/dist/jest-compat.cjs +277 -33
  15. package/dist/jest-compat.d.cts +1 -1
  16. package/dist/jest-compat.d.mts +1 -1
  17. package/dist/jest-compat.mjs +257 -33
  18. package/dist/native/assets.mjs +41 -10
  19. package/dist/native/babel-worker.mjs +4 -2
  20. package/dist/native/boundary.mjs +52 -14
  21. package/dist/native/bounded-process.mjs +110 -27
  22. package/dist/native/explain.mjs +101 -5
  23. package/dist/native/expo-module-mocks.mjs +3 -0
  24. package/dist/native/gesture-handler-buttons.mjs +148 -0
  25. package/dist/native/hooks.mjs +8 -2
  26. package/dist/native/hot-diagnostic.mjs +7 -0
  27. package/dist/native/library-jest.mjs +16 -8
  28. package/dist/native/loader.mjs +159 -2
  29. package/dist/native/metro-profile-compiler.mjs +2 -1
  30. package/dist/native/metro-profile.mjs +2 -0
  31. package/dist/native/ownership-ledger.d.mts +2 -0
  32. package/dist/native/ownership-ledger.mjs +3 -2
  33. package/dist/native/react-dedupe.d.mts +7 -0
  34. package/dist/native/react-dedupe.mjs +191 -0
  35. package/dist/native/registry-compiler.mjs +3 -2
  36. package/dist/native/registry-process.mjs +90 -12
  37. package/dist/native/registry.mjs +9 -4
  38. package/dist/native/reset.mjs +51 -26
  39. package/dist/native/resolve.mjs +5 -1
  40. package/dist/native/setup.mjs +15 -7
  41. package/dist/native/state-manifest.mjs +2 -3
  42. package/dist/native/transform.mjs +125 -3
  43. package/dist/native/worker.mjs +3 -12
  44. package/dist/node-dispatch.mjs +2 -0
  45. package/dist/preset-react.d.mts +11 -0
  46. package/dist/preset-react.mjs +121 -0
  47. package/dist/{presets-DLH7uRGA.mjs → presets-Dw0Sz9O6.mjs} +1352 -567
  48. package/dist/presets.d.mts +1 -1
  49. package/dist/presets.mjs +1 -1
  50. package/dist/setup-files-C6-77IIs.mjs +22 -0
  51. package/dist/setup.mjs +15 -13
  52. package/package.json +15 -5
  53. package/dist/memory-Couw0Esx.mjs +0 -151
  54. package/dist/native/compile-cache.mjs +0 -57
package/dist/cli.mjs CHANGED
@@ -1,8 +1,7 @@
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 unsupportedNodeMessage, B as unsupportedReactNativeMessage, C as installedManifest, D as SUPPORTED_NODE, I as belowRecommendedMessage, L as installedExpoVersion, M as validatePeerDependency, P as PEER_REQUIREMENTS, R as isBelowSupportedReactNative, S as normalizeBabelName, b as classifyBabelPlugins, c as formatHotMemoryPlan, f as detectEcosystemPackages, h as detectEngine, i as ownVitestPackage, k as satisfiesNodeRange, m as isPlainJavaScript, o as usesVitePlus, p as babelParser, r as installedViteVersion, s as createHotMemoryPlan, v as missingBabelCoreNotice, x as isKnownPlugin, y as projectBabelTrigger, z as unsupportedExpoSdkMessage } from "./host-X6VHF-a4.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
- import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-Couw0Esx.mjs";
6
5
  import { createRequire } from "node:module";
7
6
  import { fileURLToPath, pathToFileURL } from "node:url";
8
7
  import path from "node:path";
@@ -11,11 +10,12 @@ import os from "node:os";
11
10
  import { VitestNativeError } from "./errors.mjs";
12
11
  import { docsUrl } from "./docs-url.mjs";
13
12
  import { createNativeOwnershipPolicy, formatNativeOwnershipManifest } from "./native/ownership.mjs";
13
+ import { REACT_DEDUPE } from "./native/react-dedupe.mjs";
14
14
  import { relativeToRoot, rootSpellings } from "./native/root-spelling.mjs";
15
15
  import { resolveTransformPreset } from "./native/babel-preset.mjs";
16
+ import { spawn, spawnSync } from "node:child_process";
16
17
  import { HOT_STATE_MANIFEST_ENTRIES } from "./native/state-manifest.mjs";
17
18
  import { isDeepStrictEqual } from "node:util";
18
- import { spawn, spawnSync } from "node:child_process";
19
19
  import { StringDecoder } from "node:string_decoder";
20
20
  // src/cli/manifest.ts
21
21
  /**
@@ -718,6 +718,8 @@ function runDoctor(root, nodeVersion = process.versions.node) {
718
718
  * the zero-config default, and the jest-compat variant (the exact block the
719
719
  * migration guide documents, so docs and CLI can never drift apart by shape).
720
720
  */
721
+ /** The engine's own dedupe list, as config source. */
722
+ const DEDUPE_SOURCE$1 = REACT_DEDUPE.map((name) => `'${name}'`).join(", ");
721
723
  /**
722
724
  * Printed after `init` and `migrate`: the hot runtime is off by default, so a user
723
725
  * reading only the CLI output would not otherwise learn it exists or what it costs.
@@ -751,7 +753,7 @@ export default defineConfig({
751
753
  // Vitest's own mock hoister. Its position relative to reactNative() does not matter.
752
754
  plugins: [reactNative(), jestMockTransform()],
753
755
  resolve: {
754
- dedupe: ['react', 'react-test-renderer', 'react-is'],
756
+ dedupe: [${DEDUPE_SOURCE$1}],
755
757
  alias: { ...jestCompatAliases() },
756
758
  },
757
759
  test: {
@@ -1010,13 +1012,20 @@ function extractAllowlistPackages(pattern) {
1010
1012
  };
1011
1013
  const entries = [];
1012
1014
  const unparseable = [];
1015
+ const written = body.replace(/\\(.)/g, "$1");
1013
1016
  for (const alternative of topLevelAlternatives(body)) {
1014
1017
  const classified = tryExpand(alternative, true)?.filter((e) => !e.startsWith(".")).map(classify$1);
1015
1018
  if (!classified || classified.some((c) => c === null)) {
1016
1019
  unparseable.push(alternative);
1017
1020
  continue;
1018
1021
  }
1019
- for (const entry of classified) if (!entries.some((e) => e.name === entry.name && e.kind === entry.kind)) entries.push(entry);
1022
+ for (const entry of classified) {
1023
+ if (entries.some((e) => e.name === entry.name && e.kind === entry.kind)) continue;
1024
+ entries.push(written.includes(entry.name) ? entry : {
1025
+ ...entry,
1026
+ expanded: true
1027
+ });
1028
+ }
1020
1029
  }
1021
1030
  return {
1022
1031
  entries,
@@ -1728,9 +1737,12 @@ function mockFactoryForwardReads(root) {
1728
1737
  * - A snapshot serializer that only strips `jestAnimatedProps`, `jestAnimatedStyle` and
1729
1738
  * `jestInlineStyle`: Reanimated's real AnimatedComponent adds those props under Jest;
1730
1739
  * 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).
1740
+ * - A setup file that only calls `setUpTests()`, in a suite that also mocks Reanimated:
1741
+ * vitest-native registers toHaveAnimatedStyle and toHaveAnimatedProps itself, and
1742
+ * Reanimated's own versions read props its mock does not set (presets/reanimated.ts
1743
+ * keeps the engine's). A suite that calls `setUpTests()` and mocks Reanimated nowhere
1744
+ * ran the real library: migrate turns the preset off for it instead and keeps the file
1745
+ * (callsReanimatedSetUpTests, #834).
1734
1746
  */
1735
1747
  const RESOLVER = /(?:^|node_modules\/)(react-native-(?:reanimated|worklets))\/jest\/resolver(?:\.js)?$/;
1736
1748
  /** The library whose own Jest resolver `resolver` names, or null. */
@@ -1801,6 +1813,25 @@ function onlyCallsSetUpTests(source) {
1801
1813
  const statements = code.split(/[;\n]/).map((s) => s.trim()).filter(Boolean);
1802
1814
  return statements.filter((s) => /setUpTests\(\s*\)$/.test(s)).length === 1 && statements.every((s) => SETUP_STATEMENTS.some((re) => re.test(s)));
1803
1815
  }
1816
+ /**
1817
+ * Whether a setup file runs Reanimated's `setUpTests()`: it takes `setUpTests` from
1818
+ * `react-native-reanimated` and calls it, with or without arguments. Whole-line comments
1819
+ * are ignored; a file that cannot be read exactly does not count.
1820
+ */
1821
+ function callsReanimatedSetUpTests(source) {
1822
+ const code = withoutComments(source);
1823
+ if (code === null) return false;
1824
+ 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);
1825
+ }
1826
+ /**
1827
+ * Whether a setup file mocks Reanimated itself (`jest.mock('react-native-reanimated', …)`),
1828
+ * so the suite runs its mock, not the library. A commented-out mock does not count; a file
1829
+ * that cannot be read exactly does, which keeps the mock, as before.
1830
+ */
1831
+ function mocksReanimated(source) {
1832
+ const code = withoutComments(source);
1833
+ return code === null || /\bjest\.mock\(\s*(['"])react-native-reanimated\1/.test(code);
1834
+ }
1804
1835
  // src/cli/untranspiled.ts
1805
1836
  /**
1806
1837
  * Evidence that a package needs `transform`: a `.js` file under one of its entry
@@ -1907,6 +1938,8 @@ function untranspiledFile(root, pkg) {
1907
1938
  * so that a migrated project collects the same test files with the same settings
1908
1939
  * without hand edits.
1909
1940
  */
1941
+ /** The engine's own dedupe list, as config source. */
1942
+ const DEDUPE_SOURCE = REACT_DEDUPE.map((name) => `'${name}'`).join(", ");
1910
1943
  /**
1911
1944
  * Jest 30's lookup order for `jest.config.*` (jest-config's JEST_CONFIG_EXT_ORDER; Jest 29's is
1912
1945
  * the same without .mts and .cts). Jest refuses to run when more than one exists, so the order
@@ -2123,17 +2156,7 @@ function analyzeJestConfig(root) {
2123
2156
  const presetKeys = Object.keys(resolvedPreset?.own ?? {});
2124
2157
  const config = projectConfig && resolvedPreset && presetKeys.length ? withPresetSettings(projectConfig, resolvedPreset.own) : projectConfig;
2125
2158
  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
- };
2159
+ const fromJestExpo = /^jest-expo(\/(ios|android|universal))?$/.test(jestPreset ?? "");
2137
2160
  const projectSource = (file) => {
2138
2161
  if (/^(?:<rootDir>\/|\.\/)?node_modules\//.test(file)) return null;
2139
2162
  const rel = file.replace(/^<rootDir>\/?/, "");
@@ -2145,6 +2168,67 @@ function analyzeJestConfig(root) {
2145
2168
  ].find((candidate) => fs.statSync(candidate, { throwIfNoEntry: false })?.isFile());
2146
2169
  return found === void 0 ? null : fs.readFileSync(found, "utf8");
2147
2170
  };
2171
+ const setupSources = ["setupFiles", "setupFilesAfterEnv"].flatMap((key) => Array.isArray(config?.[key]) ? config[key] : []).filter((f) => typeof f === "string").map((f) => ({
2172
+ file: f,
2173
+ code: projectSource(f)
2174
+ })).filter((f) => f.code !== null);
2175
+ const realReanimatedSetup = setupSources.find(({ code }) => callsReanimatedSetUpTests(code));
2176
+ const reanimatedMocked = setupSources.some(({ code }) => mocksReanimated(code)) || [
2177
+ "",
2178
+ ".js",
2179
+ ".ts",
2180
+ ".tsx"
2181
+ ].some((ext) => fs.existsSync(path.join(root, "__mocks__", `react-native-reanimated${ext}`))) || Object.keys(config?.moduleNameMapper ?? {}).some((pattern) => {
2182
+ try {
2183
+ return new RegExp(pattern).test("react-native-reanimated");
2184
+ } catch {
2185
+ return false;
2186
+ }
2187
+ });
2188
+ const ranRealReanimated = realReanimatedSetup !== void 0 && !reanimatedMocked && activePresets(root).includes("reanimated") && libraryMockUsable(root);
2189
+ const reanimatedReal = ranRealReanimated && declaredDependencies(root).includes("react-native-reanimated");
2190
+ const navigationOff = fromJestExpo && activePresets(root).includes("navigation") && !fs.existsSync(path.join(root, "__mocks__", "@react-navigation"));
2191
+ const presetsOff = [...navigationOff ? ["navigation"] : [], ...reanimatedReal ? ["reanimated"] : []];
2192
+ const active = activePresets(root, presetsOff);
2193
+ const runsWithOwnSetup = (preset) => LIBRARY_SETUP_FILES[preset] !== void 0 && !active.includes(preset);
2194
+ const autoInlined = new Set(detectEcosystemPackages(root, [], [], [], active));
2195
+ const addAlias = (key, value) => {
2196
+ if (aliasKeys.has(key)) return false;
2197
+ aliasKeys.add(key);
2198
+ aliasEntries.push(`${JSON.stringify(key)}: ${value}`);
2199
+ aliasArray.push(`{ find: ${JSON.stringify(key)}, replacement: ${value} }`);
2200
+ return true;
2201
+ };
2202
+ const scannedSetupFiles = /* @__PURE__ */ new Set();
2203
+ let parseSetup;
2204
+ const coveredSetupLines = (file) => {
2205
+ const resolved = path.resolve(root, file.replace(/^<rootDir>\/?/, ""));
2206
+ if (scannedSetupFiles.has(resolved)) return [];
2207
+ scannedSetupFiles.add(resolved);
2208
+ const code = projectSource(file);
2209
+ if (code === null) return [];
2210
+ parseSetup ??= babelParser(root);
2211
+ const statements = parseSetup ? setupStatements(parseSetup, code) : [];
2212
+ const lines = [];
2213
+ for (const { mocked, request, imported, factory } of statements) {
2214
+ const pkg = /^(@[^/]+\/[^/]+|[^@./][^/]*)/.exec(mocked ?? request ?? "")?.[1];
2215
+ const preset = mocked !== void 0 ? presetShadowing(mocked) : pkg && presetShadowing(pkg);
2216
+ if (!pkg || !preset) continue;
2217
+ if (!active.includes(preset) && !runsWithOwnSetup(preset)) continue;
2218
+ const shown = mocked ? `jest.mock('${mocked}')` : imported ? `import '${request}'` : `require('${request}')`;
2219
+ if (factory && keepsPartOfModule(factory)) {
2220
+ 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.`);
2221
+ continue;
2222
+ }
2223
+ const ownSetup = LIBRARY_SETUP_FILES[preset];
2224
+ if (active.includes(preset)) lines.push(`${file}: ${shown} — the auto-detected ${preset} preset shadows ${pkg}; delete the line.`);
2225
+ else {
2226
+ const isOwnSetup = request !== void 0 && request.replace(/\.js$/, "") === ownSetup?.replace(/\.js$/, "");
2227
+ 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.`);
2228
+ }
2229
+ }
2230
+ return lines;
2231
+ };
2148
2232
  const reanimatedActive = active.includes("reanimated");
2149
2233
  const absolutePath = (relative) => {
2150
2234
  needsUrlImport = true;
@@ -2182,14 +2266,16 @@ function analyzeJestConfig(root) {
2182
2266
  if (/react-native\/jest\/setup/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
2183
2267
  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
2268
  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.`);
2269
+ 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
2270
  else if (/jest-expo/.test(f)) attention.push(`${key}: '${f}' — ${expoPresetCoverage()}.`);
2187
2271
  else if (f.startsWith("<rootDir>")) {
2188
2272
  setupFiles.push(absolutePath(f.replace(/^<rootDir>\/?/, "./")));
2189
2273
  automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
2274
+ presetCovered.push(...coveredSetupLines(f));
2190
2275
  } else {
2191
2276
  setupFiles.push(JSON.stringify(f));
2192
2277
  automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
2278
+ presetCovered.push(...coveredSetupLines(f));
2193
2279
  }
2194
2280
  }
2195
2281
  }
@@ -2242,7 +2328,6 @@ function analyzeJestConfig(root) {
2242
2328
  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
2329
  else classifyAllowlist(root, entries, active, autoInlined, {
2244
2330
  automatic,
2245
- presetCovered,
2246
2331
  transformPkgs
2247
2332
  });
2248
2333
  }
@@ -2409,10 +2494,10 @@ function analyzeJestConfig(root) {
2409
2494
  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
2495
  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
2496
  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
- }
2497
+ if (presetsOff.length) pluginOptions.push(`presets: { ${presetsOff.map((p) => `${p}: false`).join(", ")} }`);
2498
+ 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 }.`);
2499
+ 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.`);
2500
+ if (navigationOff) automatic.push("jest-expo renders the real React Navigation → presets: { navigation: false }, so screens keep running in real navigators.");
2416
2501
  const factoryReads = mockFactoryForwardReads(root);
2417
2502
  if (factoryReads.length) {
2418
2503
  const shown = factoryReads.slice(0, 5).map((r) => `${r.file}:${r.line} (jest.mock('${r.module}') reads ${r.names.join(", ")})`);
@@ -2493,7 +2578,7 @@ export default defineConfig({
2493
2578
  transformCall
2494
2579
  ].join(", ")}],
2495
2580
  resolve: {
2496
- dedupe: ['react', 'react-test-renderer', 'react-is'],
2581
+ dedupe: [${DEDUPE_SOURCE}],
2497
2582
  alias: ${aliasSource},
2498
2583
  },
2499
2584
  test: {
@@ -2506,6 +2591,64 @@ export default defineConfig({
2506
2591
  ok: source !== null
2507
2592
  };
2508
2593
  }
2594
+ const isAstNode = (v) => !!v && typeof v === "object" && typeof v.type === "string";
2595
+ const stringValue = (n) => isAstNode(n) && n.type === "StringLiteral" ? n.value : void 0;
2596
+ /**
2597
+ * A setup file's top-level `jest.mock('<id>', …)`, `require('<id>')` and `import '<id>'`
2598
+ * statements. Nothing when the file does not parse.
2599
+ */
2600
+ function setupStatements(parse, code) {
2601
+ let ast;
2602
+ try {
2603
+ ast = parse(code, {
2604
+ sourceType: "unambiguous",
2605
+ plugins: ["typescript", "jsx"],
2606
+ allowReturnOutsideFunction: true,
2607
+ allowAwaitOutsideFunction: true
2608
+ });
2609
+ } catch {
2610
+ return [];
2611
+ }
2612
+ return (ast.program?.body ?? []).flatMap((statement) => {
2613
+ if (statement.type === "ImportDeclaration") {
2614
+ const request = stringValue(statement.source);
2615
+ const named = statement.specifiers?.length ?? 0;
2616
+ return request !== void 0 && named === 0 ? [{
2617
+ request,
2618
+ imported: true
2619
+ }] : [];
2620
+ }
2621
+ if (statement.type !== "ExpressionStatement") return [];
2622
+ const call = statement.expression;
2623
+ if (!isAstNode(call) || call.type !== "CallExpression") return [];
2624
+ const callee = call.callee;
2625
+ const args = call.arguments;
2626
+ const id = stringValue(args[0]);
2627
+ if (id === void 0) return [];
2628
+ if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.object.name === "jest" && callee.property.name === "mock") return [{
2629
+ mocked: id,
2630
+ factory: args[1]
2631
+ }];
2632
+ if (callee.type === "Identifier" && callee.name === "require" && args.length === 1) return [{ request: id }];
2633
+ return [];
2634
+ });
2635
+ }
2636
+ /** Whether a mock factory keeps part of the real module: `jest.requireActual`, a spread. */
2637
+ function keepsPartOfModule(node) {
2638
+ if (Array.isArray(node)) return node.some(keepsPartOfModule);
2639
+ if (!isAstNode(node)) return false;
2640
+ if (node.type === "SpreadElement") return true;
2641
+ if (node.type === "MemberExpression" && !node.computed && node.property.name === "requireActual") return true;
2642
+ return Object.entries(node).some(([key, value]) => ![
2643
+ "loc",
2644
+ "start",
2645
+ "end",
2646
+ "leadingComments",
2647
+ "trailingComments",
2648
+ "innerComments",
2649
+ "extra"
2650
+ ].includes(key) && typeof value === "object" && keepsPartOfModule(value));
2651
+ }
2509
2652
  /**
2510
2653
  * What each package a transformIgnorePatterns allowlist lets through needs here.
2511
2654
  * Jest compiles nothing in node_modules unless allowed, so its allowlists mix React
@@ -2517,7 +2660,9 @@ export default defineConfig({
2517
2660
  * Prefix and scope entries are matched against the project's declared dependencies.
2518
2661
  */
2519
2662
  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)]);
2663
+ const declared = new Set(declaredDependencies(root));
2664
+ const candidates = /* @__PURE__ */ new Set([...declared, ...entries.filter((e) => e.kind === "exact").map((e) => e.name)]);
2665
+ const spelled = new Set(entries.filter((e) => e.kind === "exact" && !e.expanded).map((e) => e.name));
2521
2666
  const groups = {
2522
2667
  rn: [],
2523
2668
  detected: [],
@@ -2530,8 +2675,9 @@ function classifyAllowlist(root, entries, active, autoInlined, out) {
2530
2675
  if (pkg === "react-native" || pkg.startsWith("@react-native/")) groups.rn.push(pkg);
2531
2676
  else if (preset && active.includes(preset)) shadowed.set(preset, [...shadowed.get(preset) ?? [], pkg]);
2532
2677
  else if (autoInlined.has(pkg)) groups.detected.push(pkg);
2533
- else if (!installedManifest(root, pkg)) groups.absent.push(pkg);
2534
- else {
2678
+ else if (!installedManifest(root, pkg)) {
2679
+ if (declared.has(pkg) || spelled.has(pkg)) groups.absent.push(pkg);
2680
+ } else {
2535
2681
  const evidence = untranspiledFile(root, pkg);
2536
2682
  if (evidence) {
2537
2683
  out.transformPkgs.push(pkg);
@@ -2540,7 +2686,7 @@ function classifyAllowlist(root, entries, active, autoInlined, out) {
2540
2686
  }
2541
2687
  }
2542
2688
  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.`);
2689
+ for (const [preset, pkgs] of shadowed) out.automatic.push(`transformIgnorePatterns allows ${list(pkgs)} — shadowed by the auto-detected ${preset} preset; nothing to do.`);
2544
2690
  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
2691
  if (groups.absent.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.absent)} — not installed; nothing to do.`);
2546
2692
  }
@@ -27,6 +27,12 @@ export interface ProjectContextFields {
27
27
  packageDirs?: { root: string; dirs: Record<string, string | null> };
28
28
  ownershipGuard?: { mode: "warn" | "error"; allow: { path: string; reason: string }[] };
29
29
  projectDirs?: string[];
30
+ /**
31
+ * `[dir, name, parent]` for each installed dependency of a package found only by the
32
+ * installed scan that is not compiled: Node fails a file of one by name when it cannot
33
+ * run as published (#883).
34
+ */
35
+ scanFoundDependencies?: [string, string, string][];
30
36
  requireAliases?: [string, string][];
31
37
  /** The project sets test.restoreMocks: jest-compat restores jest.replaceProperty() before each test. */
32
38
  restoreMocks?: true;
package/dist/context.mjs CHANGED
@@ -52,6 +52,11 @@ const SCHEMA = {
52
52
  },
53
53
  ownershipGuard: { valid: object },
54
54
  projectDirs: { valid: strings },
55
+ scanFoundDependencies: {
56
+ valid: (v) =>
57
+ Array.isArray(v) &&
58
+ v.every((e) => Array.isArray(e) && e.length === 3 && strings(e) && absolute(e[0])),
59
+ },
55
60
  requireAliases: {
56
61
  valid: (v) =>
57
62
  Array.isArray(v) && v.every((e) => Array.isArray(e) && e.length === 2 && strings(e)),
package/dist/errors.d.mts CHANGED
@@ -35,6 +35,7 @@ export type VitestNativeErrorCode =
35
35
  | "METRO_PROFILE_INVALID"
36
36
  | "TRANSFORM_FAILED"
37
37
  | "UNTRANSPILED_PACKAGE"
38
+ | "UNDECLARED_DEPENDENCY_UNCOMPILED"
38
39
  | "HOT_WORKER_ENV"
39
40
  | "HOT_WORKER_PRELOAD"
40
41
  | "HOT_RUNTIME_UNAVAILABLE"
@@ -51,12 +52,16 @@ export type VitestNativeErrorCode =
51
52
  | "PROJECT_BABEL_COMMONJS"
52
53
  | "PRESET_UNAVAILABLE"
53
54
  | "PRESET_NOT_PREPARED"
55
+ | "PRESET_REACT_MISMATCH"
54
56
  | "WRONG_ENGINE_FOR_HELPER"
55
57
  | "HELPERS_BEFORE_SETUP"
56
58
  | "JEST_API_UNSUPPORTED"
57
59
  | "REQUIRE_ACTUAL_ALIAS_UNSUPPORTED"
58
60
  | "JEST_MOCK_FACTORY_CYCLE"
61
+ | "JEST_MOCK_MISSING_EXPORT"
59
62
  | "JEST_COMPAT_SETUP_MISSING"
63
+ | "JEST_BINDING_NOT_FOLLOWED"
64
+ | "JEST_MOCK_VI_UNAVAILABLE"
60
65
  | "BABEL_IGNORES_FILE"
61
66
  | "LIBRARY_REGISTRY_FAILED"
62
67
  | "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);