vitest-native 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +921 -0
  2. package/README.md +33 -1
  3. package/dist/cli.cjs +185 -31
  4. package/dist/cli.mjs +182 -28
  5. package/dist/ecosystem-BJzJU3Cf.cjs +568 -0
  6. package/dist/ecosystem-C4qT_vl3.mjs +506 -0
  7. package/dist/errors-B3lJK46O.cjs +75 -0
  8. package/dist/errors-CxoBUfVJ.mjs +64 -0
  9. package/dist/errors.d.mts +46 -0
  10. package/dist/errors.mjs +78 -0
  11. package/dist/helpers.cjs +6 -23
  12. package/dist/helpers.d.cts +0 -6
  13. package/dist/helpers.d.mts +0 -6
  14. package/dist/helpers.mjs +6 -23
  15. package/dist/{index-CEgRDdhd.d.cts → index-CrMeE8rd.d.mts} +14 -9
  16. package/dist/{index-j-0tueBr.d.mts → index-DIMbjH8R.d.cts} +15 -7
  17. package/dist/index.d.mts +8 -7
  18. package/dist/index.mjs +307 -91
  19. package/dist/jest-compat/interop.mjs +15 -0
  20. package/dist/jest-compat/setup.mjs +102 -7
  21. package/dist/jest-compat.cjs +4 -4
  22. package/dist/jest-compat.d.cts +0 -1
  23. package/dist/jest-compat.d.mts +0 -1
  24. package/dist/jest-compat.mjs +2 -2
  25. package/dist/matchers.cjs +16 -7
  26. package/dist/matchers.mjs +16 -7
  27. package/dist/native/hooks.mjs +152 -13
  28. package/dist/native/loader.mjs +36 -11
  29. package/dist/native/match.d.mts +33 -0
  30. package/dist/native/match.mjs +94 -22
  31. package/dist/native/module-reset.mjs +63 -0
  32. package/dist/native/registry.mjs +110 -13
  33. package/dist/native/resolve.d.mts +22 -0
  34. package/dist/native/resolve.mjs +21 -13
  35. package/dist/native/runner.mjs +21 -0
  36. package/dist/native/setup.mjs +4 -2
  37. package/dist/native/transform.mjs +108 -3
  38. package/dist/native/worker.mjs +59 -16
  39. package/dist/{pool-DzsEo9vv.cjs → pool-BU-1ecIF.cjs} +7 -6
  40. package/dist/{pool-CJmjRgsB.mjs → pool-Bcxn9a3I.mjs} +4 -3
  41. package/dist/{preset-map-CG4FMtsl.cjs → preset-map-BoG19dLa.cjs} +1 -1
  42. package/dist/{preset-map-CNsZKfvu.mjs → preset-map-DuX0ocdn.mjs} +1 -1
  43. package/dist/{presets-C4faM3ds.cjs → presets-CwO_c4aL.cjs} +224 -55
  44. package/dist/{presets-CuDrNA_W.mjs → presets-IStcJEOa.mjs} +216 -53
  45. package/dist/presets.d.mts +2 -2
  46. package/dist/presets.mjs +2 -2
  47. package/dist/rntl-matchers.d.ts +35 -0
  48. package/dist/{chunk-CjcI7cDX.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
  49. package/dist/{chunk-CZWwpsFl.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  50. package/dist/serializer.cjs +34 -4
  51. package/dist/serializer.mjs +34 -4
  52. package/dist/setup.d.mts +1 -1
  53. package/dist/setup.mjs +237 -74
  54. package/docs/release-readiness.md +22 -5
  55. package/docs/versioning.md +133 -0
  56. package/package.json +38 -46
  57. package/dist/ecosystem-BIWaVwYL.cjs +0 -294
  58. package/dist/ecosystem-EFtHnKS9.mjs +0 -256
  59. package/dist/index.cjs +0 -788
  60. package/dist/index.d.cts +0 -14
  61. package/dist/presets.cjs +0 -18
  62. package/dist/presets.d.cts +0 -2
  63. package/dist/setup.cjs +0 -2702
  64. package/dist/setup.d.cts +0 -1
package/README.md CHANGED
@@ -476,6 +476,7 @@ export default defineConfig({
476
476
  | `presets.expo()` | Expo modules |
477
477
  | `presets.deviceInfo()` | react-native-device-info |
478
478
  | `presets.mmkv()` | react-native-mmkv |
479
+ | `presets.netInfo()` | @react-native-community/netinfo |
479
480
  | `presets.svg()` | react-native-svg |
480
481
  | `presets.webview()` | react-native-webview |
481
482
  | `presets.vectorIcons()` | react-native-vector-icons |
@@ -634,6 +635,33 @@ When supported `@testing-library/react-native` 12–14 is installed, `vitest-nat
634
635
  auto-registers its custom matchers across each major's export layout. No manual
635
636
  `extend(matchers)` call or setup file is needed.
636
637
 
638
+ ### TypeScript
639
+
640
+ The matchers run without any setup, but their **types** need one line. RNTL declares
641
+ them only for Jest — it augments the global `jest` namespace and `@jest/expect`, and
642
+ neither reaches Vitest's `Assertion` — so without this they are
643
+ `Property 'toHaveTextContent' does not exist on type 'Assertion<...>'` even though the
644
+ assertion works at runtime.
645
+
646
+ Reference the types once, anywhere in the project:
647
+
648
+ ```ts
649
+ /// <reference types="vitest-native/rntl-matchers" />
650
+ ```
651
+
652
+ or add it to `compilerOptions.types` in `tsconfig.json`:
653
+
654
+ ```json
655
+ { "compilerOptions": { "types": ["vitest-native/rntl-matchers"] } }
656
+ ```
657
+
658
+ It is opt-in rather than automatic because `@testing-library/react-native` is an
659
+ optional peer: a type import of an absent package is invisible under
660
+ `skipLibCheck: true` (React Native's default) but reports `TS2307` under
661
+ `skipLibCheck: false`, which would break projects that use the mock engine without
662
+ RNTL. Referencing nothing loads nothing — the file is not part of the program unless
663
+ asked for.
664
+
637
665
  The following matchers become available on `expect()`:
638
666
 
639
667
  | Matcher | Description |
@@ -855,6 +883,10 @@ Every release must pass:
855
883
  Current React Native edge releases are also tested weekly. See
856
884
  [the release-readiness policy](docs/release-readiness.md) for the exact gates and stability labels.
857
885
 
886
+ For what is *promised* rather than what is tested — which exports and options are protected by
887
+ semver, which are experimental, how the version ranges above may move, and what 1.0 will mean —
888
+ see [versioning and stability](docs/versioning.md).
889
+
858
890
  ---
859
891
 
860
892
  ## Requirements
@@ -864,7 +896,7 @@ Current React Native edge releases are also tested weekly. See
864
896
  | `react` | >= 18; use RN's matching React version |
865
897
  | `vite` | ^6.4.2, ^7.3.2, or ^8.0.5 |
866
898
  | `vitest` | 4.x |
867
- | `node` | >= 20; RN/RNTL may impose a higher floor |
899
+ | `node` | >= 20.19; RN/RNTL may impose a higher floor |
868
900
  | `react-native` (native engine) | 0.81–0.86 validated |
869
901
  | `@react-native/babel-preset` (native engine) | Match the installed React Native minor |
870
902
  | `@testing-library/react-native` (optional) | 12.x, 13.x, or 14.x |
package/dist/cli.cjs CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_chunk = require("./chunk-CZWwpsFl.cjs");
4
- const require_ecosystem = require("./ecosystem-BIWaVwYL.cjs");
5
- const require_preset_map = require("./preset-map-CG4FMtsl.cjs");
6
- let node_path = require("node:path");
7
- node_path = require_chunk.__toESM(node_path, 1);
3
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
4
+ const require_ecosystem = require("./ecosystem-BJzJU3Cf.cjs");
5
+ const require_preset_map = require("./preset-map-BoG19dLa.cjs");
8
6
  let node_fs = require("node:fs");
9
- node_fs = require_chunk.__toESM(node_fs, 1);
7
+ node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
8
+ let node_path = require("node:path");
9
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
10
10
  let node_module = require("node:module");
11
11
  //#region src/cli/doctor.ts
12
12
  /**
@@ -21,17 +21,150 @@ function packageVersion(root, name) {
21
21
  return null;
22
22
  }
23
23
  }
24
+ /**
25
+ * The supported Node floor, as [major, minor], read from this package's own
26
+ * `engines.node`. Single source: the manifest is what a package manager enforces
27
+ * at install time, so a diagnostic must not carry its own copy of the number.
28
+ */
29
+ function nodeFloor() {
30
+ const fallback = [20, 19];
31
+ try {
32
+ const manifest = JSON.parse(node_fs.default.readFileSync(new URL("../../package.json", require("url").pathToFileURL(__filename).href), "utf8"));
33
+ const match = /(\d+)\.(\d+)/.exec(manifest.engines?.node ?? "");
34
+ return match ? [Number(match[1]), Number(match[2])] : fallback;
35
+ } catch {
36
+ return fallback;
37
+ }
38
+ }
39
+ /**
40
+ * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
41
+ * is used when there is none.
42
+ *
43
+ * The vite.config entries were missing, so a correct setup that configures Vitest
44
+ * from vite.config.ts — normal in projects that already had Vite — was told "no
45
+ * vitest.config.* found — run `vitest-native init`". Following that produces a
46
+ * second config which then TAKES PRECEDENCE over the working one, so the advice
47
+ * did not just misreport, it would have broken the project.
48
+ */
49
+ const CONFIG_FILES = [
50
+ "vitest.config.ts",
51
+ "vitest.config.mts",
52
+ "vitest.config.js",
53
+ "vitest.config.mjs",
54
+ "vitest.config.cts",
55
+ "vitest.config.cjs",
56
+ "vite.config.ts",
57
+ "vite.config.mts",
58
+ "vite.config.js",
59
+ "vite.config.mjs",
60
+ "vite.config.cts",
61
+ "vite.config.cjs"
62
+ ];
24
63
  function findConfigFile(root) {
25
- for (const name of [
26
- "vitest.config.ts",
27
- "vitest.config.mts",
28
- "vitest.config.js",
29
- "vitest.config.mjs",
30
- "vitest.config.cts",
31
- "vitest.config.cjs"
32
- ]) if (node_fs.default.existsSync(node_path.default.join(root, name))) return name;
64
+ for (const name of CONFIG_FILES) if (node_fs.default.existsSync(node_path.default.join(root, name))) return name;
33
65
  return null;
34
66
  }
67
+ /** Source with comments removed, so a mention inside one cannot be mistaken for use. */
68
+ function withoutComments(source) {
69
+ return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
70
+ }
71
+ /**
72
+ * Whether a config is built on one imported from elsewhere — a shared preset in a
73
+ * workspace, typically. Such a file legitimately never mentions vitest-native, and
74
+ * reporting it as unconfigured is a false alarm on a working project.
75
+ */
76
+ function extendsSharedConfig(source) {
77
+ const code = withoutComments(source);
78
+ const imports = [...code.matchAll(/import\s+([^;]+?)\s+from\s*["']([^"'.][^"']*)["']/g)];
79
+ for (const [, clause, specifier] of imports) {
80
+ if (specifier === "vitest" || specifier.startsWith("vitest/")) continue;
81
+ const bindings = [...clause.matchAll(/([A-Za-z_$][\w$]*)/g)].map((m) => m[1]);
82
+ for (const binding of bindings) {
83
+ if (binding === "defineConfig" || binding === "default") continue;
84
+ if (new RegExp(`export\\s+default\\s+${binding}\\s*;?\\s*$`, "m").test(code)) return true;
85
+ if (new RegExp(`\\bmergeConfig\\s*\\(\\s*${binding}\\b`).test(code)) return true;
86
+ }
87
+ }
88
+ return false;
89
+ }
90
+ /**
91
+ * Whether a config genuinely uses the plugin.
92
+ *
93
+ * This was a substring test — `content.includes("vitest-native")` — so a config
94
+ * whose only mention was a `// TODO: migrate to vitest-native` comment reported
95
+ * "uses vitest-native" and "No blocking problems found", on a project where every
96
+ * React Native import would fail. Diagnosing that is the entire job of this
97
+ * command.
98
+ *
99
+ * The binding name is read from the import rather than assumed, so an aliased
100
+ * import still counts as used; when the import shape is not one of the forms
101
+ * below, the import alone is accepted rather than risking a false alarm on a
102
+ * working project.
103
+ */
104
+ function analyzeConfigUsage(source) {
105
+ const code = withoutComments(source);
106
+ const named = /import\s*\{([^}]*)\}\s*from\s*["']vitest-native["']/.exec(code);
107
+ const namespaced = /import\s*\*\s*as\s*([A-Za-z_$][\w$]*)\s*from\s*["']vitest-native["']/.exec(code);
108
+ const required = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*["']vitest-native["']\s*\)/.exec(code);
109
+ const bindingFrom = (clause) => {
110
+ const entry = /\breactNative\b(?:\s*(?::|as)\s*([A-Za-z_$][\w$]*))?/.exec(clause);
111
+ return entry ? entry[1] ?? "reactNative" : null;
112
+ };
113
+ if (named || required) {
114
+ const binding = bindingFrom((named ?? required)[1]);
115
+ if (!binding) return {
116
+ imports: true,
117
+ invokes: true
118
+ };
119
+ return {
120
+ imports: true,
121
+ invokes: new RegExp(`\\b${binding}\\s*\\(`).test(code)
122
+ };
123
+ }
124
+ if (namespaced) return {
125
+ imports: true,
126
+ invokes: new RegExp(`\\b${namespaced[1]}\\.\\w+\\s*\\(`).test(code)
127
+ };
128
+ if (/from\s*["']vitest-native["']|require\(\s*["']vitest-native["']\s*\)/.test(code)) return {
129
+ imports: true,
130
+ invokes: true
131
+ };
132
+ return {
133
+ imports: false,
134
+ invokes: false
135
+ };
136
+ }
137
+ /**
138
+ * The directory a test run would actually resolve from.
139
+ *
140
+ * `doctor` resolved peers from its own working directory. In a workspace that is
141
+ * frequently not where the Vitest config lives, and under pnpm a package's
142
+ * node_modules holds only its DECLARED dependencies — so a hoisted
143
+ * `@react-native/babel-preset` does not resolve from the package even though the
144
+ * real run finds it. The result was `doctor` reporting "engine 'auto' resolves to
145
+ * MOCK" for a project whose run banner said native.
146
+ *
147
+ * This is a FALLBACK, not a replacement. Node resolution walks upward, so the
148
+ * directory the command was invoked in already sees its own dependencies AND
149
+ * everything declared above it — resolving from higher up can only see less. Using
150
+ * the config root unconditionally lost dependencies a package declared itself, and
151
+ * reported a missing peer for a project that had one: the inverse of the bug this
152
+ * was written for.
153
+ *
154
+ * So the invocation directory is tried first, and this is consulted only when
155
+ * something fails to resolve there — which is the case where the command was run
156
+ * above the package that declares it.
157
+ */
158
+ function resolutionRoot(start, exists = node_fs.default.existsSync) {
159
+ let dir = start;
160
+ for (;;) {
161
+ if (CONFIG_FILES.some((name) => exists(node_path.default.join(dir, name))) && exists(node_path.default.join(dir, "package.json"))) return dir;
162
+ if (exists(node_path.default.join(dir, ".git"))) return start;
163
+ const parent = node_path.default.dirname(dir);
164
+ if (parent === dir) return start;
165
+ dir = parent;
166
+ }
167
+ }
35
168
  function runDoctor(root, nodeVersion = process.versions.node) {
36
169
  const lines = [];
37
170
  let ok = true;
@@ -41,29 +174,42 @@ function runDoctor(root, nodeVersion = process.versions.node) {
41
174
  ok = false;
42
175
  lines.push(` ✗ ${s}`);
43
176
  };
177
+ const configRoot = resolutionRoot(root);
178
+ const resolvesHere = (name) => packageVersion(root, name) !== null;
179
+ const rootFor = (name) => resolvesHere(name) || configRoot === root ? root : configRoot;
44
180
  lines.push(`vitest-native doctor — ${root}`);
45
181
  lines.push("", "Runtime");
46
182
  const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
47
- if (nodeMajorMinor[0] >= 20) pass(`Node ${nodeVersion} (floor: 20)`);
48
- else fail(`Node ${nodeVersion} — vitest-native requires Node >= 20.`);
183
+ const [floorMajor, floorMinor] = nodeFloor();
184
+ const floorText = `${floorMajor}.${floorMinor}`;
185
+ if (nodeMajorMinor[0] > floorMajor || nodeMajorMinor[0] === floorMajor && nodeMajorMinor[1] >= floorMinor) pass(`Node ${nodeVersion} (floor: ${floorText})`);
186
+ else fail(`Node ${nodeVersion} — vitest-native requires Node >= ${floorText}.`);
49
187
  lines.push("", "Peer dependencies");
50
- for (const { name, minimum, maximumMajor, minimumByMajor } of require_ecosystem.PEER_REQUIREMENTS) {
51
- const error = require_ecosystem.validatePeerDependency(name, minimum, root, maximumMajor, minimumByMajor);
188
+ for (const { name, minimum, maximumMajor, minimumByMajor, optional } of require_ecosystem.PEER_REQUIREMENTS) {
189
+ if (optional) continue;
190
+ const from = rootFor(name);
191
+ const error = require_ecosystem.validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor);
52
192
  if (error) fail(error);
53
- else pass(`${name} ${packageVersion(root, name)}`);
193
+ else {
194
+ pass(`${name} ${packageVersion(from, name)}`);
195
+ if (from !== root) lines.push(` (resolved from ${from}, not from here)`);
196
+ }
54
197
  }
55
198
  lines.push("", "Engine");
56
- const rnVersion = packageVersion(root, "react-native");
57
- if (require_ecosystem.detectEngine("auto", root).engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with @react-native/babel-preset + @babel/core present.`);
199
+ const rnVersion = packageVersion(rootFor("react-native"), "react-native");
200
+ if (require_ecosystem.detectEngine("auto", rootFor("@react-native/babel-preset")).engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with @react-native/babel-preset + @babel/core present.`);
58
201
  else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but @react-native/babel-preset and/or @babel/core do not resolve. Install both as devDependencies to run the real-RN native engine.`);
59
202
  else warn("engine 'auto' resolves to MOCK: react-native is not installed. That is fine for pure-logic suites; install react-native (+ its babel preset) for the native engine.");
60
203
  lines.push("", "Testing library");
61
- const rntl = packageVersion(root, "@testing-library/react-native");
204
+ const rntl = packageVersion(rootFor("@testing-library/react-native"), "@testing-library/react-native");
62
205
  if (!rntl) warn("@testing-library/react-native not found — optional, but required for render()/screen queries.");
63
206
  else {
64
207
  const rntlMajor = Number(rntl.split(".")[0]);
65
- if (rntlMajor < 12 || rntlMajor >= 15) fail(`@testing-library/react-native ${rntl} — supported range is >=12 <15.`);
208
+ const rntlReq = require_ecosystem.PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
209
+ const rntlError = rntlReq && require_ecosystem.validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
210
+ if (rntlError) warn(rntlError);
66
211
  else if (rntlMajor >= 14 && (nodeMajorMinor[0] < 22 || nodeMajorMinor[0] === 22 && nodeMajorMinor[1] < 13)) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
212
+ else if (rntlMajor >= 14 && !packageVersion(rootFor("test-renderer"), "test-renderer")) fail(`@testing-library/react-native ${rntl} requires the 'test-renderer' package, which is not installed. Every render() will fail with "Cannot find module 'test-renderer'". Install it:\n\n npm install -D test-renderer\n`);
67
213
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
68
214
  }
69
215
  lines.push("", "Auto-detected presets");
@@ -75,18 +221,21 @@ function runDoctor(root, nodeVersion = process.versions.node) {
75
221
  } catch {}
76
222
  if (detected.length) for (const d of detected) pass(d);
77
223
  else lines.push(" (none — no preset-covered packages installed)");
78
- const expo = packageVersion(root, "expo");
224
+ const expo = packageVersion(rootFor("expo"), "expo");
79
225
  if (expo) {
80
226
  lines.push("", "Expo");
81
227
  warn(`expo ${expo} detected. Expo-module components work via the auto-detected preset; suites that import Expo CORE internals (expo-router setups, dev-client wiring) can hit known limits — see the Jest migration guide's Expo notes.`);
82
228
  }
83
229
  lines.push("", "Config");
84
- const configFile = findConfigFile(root);
230
+ const configFile = findConfigFile(configRoot);
85
231
  if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
86
232
  else {
87
- const content = node_fs.default.readFileSync(node_path.default.join(root, configFile), "utf8");
88
- if (content.includes("vitest-native") || content.includes("reactNative(")) pass(`${configFile} uses vitest-native.`);
89
- else warn(`${configFile} exists but does not reference vitest-native.`);
233
+ const content = node_fs.default.readFileSync(node_path.default.join(configRoot, configFile), "utf8");
234
+ const usage = analyzeConfigUsage(content);
235
+ if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
236
+ else if (usage.imports) warn(`${configFile} imports vitest-native but never calls reactNative() — the plugin is not in \`plugins: [...]\`, so React Native imports will not resolve.`);
237
+ else if (extendsSharedConfig(content)) lines.push(` · ${configFile} builds on a shared config, so this cannot tell from here whether the plugin is wired up. Check the config it extends.`);
238
+ else warn(`${configFile} exists but does not import vitest-native` + (content.includes("vitest-native") ? " (it is only mentioned in a comment)" : "") + " — add `reactNative()` to `plugins: [...]`, or run `vitest-native init`.");
90
239
  }
91
240
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
92
241
  return {
@@ -119,8 +268,9 @@ import { reactNative } from 'vitest-native'
119
268
  import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
120
269
 
121
270
  export default defineConfig({
122
- // jestMockTransform() must come AFTER reactNative() and stay normal-order:
123
- // it rewrites top-level jest.mock(...) into hoisted vi.mock(...).
271
+ // jestMockTransform() rewrites top-level jest.mock(...) into hoisted vi.mock(...).
272
+ // Leave it without an \`enforce\`: it has to run after Vite strips TS/JSX and before
273
+ // Vitest's own mock hoister. Its position relative to reactNative() does not matter.
124
274
  plugins: [reactNative(), jestMockTransform()],
125
275
  resolve: {
126
276
  dedupe: ['react', 'react-test-renderer', 'react-is'],
@@ -282,7 +432,11 @@ function analyzeJestConfig(root) {
282
432
  const files = take(key);
283
433
  if (!files?.length) continue;
284
434
  for (const f of files) if (/react-native\/jest\/setup|jest-expo/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
285
- else {
435
+ else if (f.startsWith("<rootDir>")) {
436
+ setupFiles.push(`fileURLToPath(new URL(${JSON.stringify(f.replace(/^<rootDir>\/?/, "./"))}, import.meta.url))`);
437
+ needsUrlImport = true;
438
+ automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
439
+ } else {
286
440
  setupFiles.push(JSON.stringify(f));
287
441
  automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
288
442
  }
package/dist/cli.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { a as validatePeerDependency, n as detectEngine, r as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-EFtHnKS9.mjs";
3
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-CNsZKfvu.mjs";
2
+ import { l as validatePeerDependency, n as detectEngine, s as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-C4qT_vl3.mjs";
3
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
4
4
  import { createRequire } from "node:module";
5
- import path from "node:path";
6
5
  import fs from "node:fs";
6
+ import path from "node:path";
7
7
  //#region src/cli/doctor.ts
8
8
  /**
9
9
  * `vitest-native doctor` — diagnose the project's environment: peer versions,
@@ -17,17 +17,150 @@ function packageVersion(root, name) {
17
17
  return null;
18
18
  }
19
19
  }
20
+ /**
21
+ * The supported Node floor, as [major, minor], read from this package's own
22
+ * `engines.node`. Single source: the manifest is what a package manager enforces
23
+ * at install time, so a diagnostic must not carry its own copy of the number.
24
+ */
25
+ function nodeFloor() {
26
+ const fallback = [20, 19];
27
+ try {
28
+ const manifest = JSON.parse(fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
29
+ const match = /(\d+)\.(\d+)/.exec(manifest.engines?.node ?? "");
30
+ return match ? [Number(match[1]), Number(match[2])] : fallback;
31
+ } catch {
32
+ return fallback;
33
+ }
34
+ }
35
+ /**
36
+ * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
37
+ * is used when there is none.
38
+ *
39
+ * The vite.config entries were missing, so a correct setup that configures Vitest
40
+ * from vite.config.ts — normal in projects that already had Vite — was told "no
41
+ * vitest.config.* found — run `vitest-native init`". Following that produces a
42
+ * second config which then TAKES PRECEDENCE over the working one, so the advice
43
+ * did not just misreport, it would have broken the project.
44
+ */
45
+ const CONFIG_FILES = [
46
+ "vitest.config.ts",
47
+ "vitest.config.mts",
48
+ "vitest.config.js",
49
+ "vitest.config.mjs",
50
+ "vitest.config.cts",
51
+ "vitest.config.cjs",
52
+ "vite.config.ts",
53
+ "vite.config.mts",
54
+ "vite.config.js",
55
+ "vite.config.mjs",
56
+ "vite.config.cts",
57
+ "vite.config.cjs"
58
+ ];
20
59
  function findConfigFile(root) {
21
- for (const name of [
22
- "vitest.config.ts",
23
- "vitest.config.mts",
24
- "vitest.config.js",
25
- "vitest.config.mjs",
26
- "vitest.config.cts",
27
- "vitest.config.cjs"
28
- ]) if (fs.existsSync(path.join(root, name))) return name;
60
+ for (const name of CONFIG_FILES) if (fs.existsSync(path.join(root, name))) return name;
29
61
  return null;
30
62
  }
63
+ /** Source with comments removed, so a mention inside one cannot be mistaken for use. */
64
+ function withoutComments(source) {
65
+ return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
66
+ }
67
+ /**
68
+ * Whether a config is built on one imported from elsewhere — a shared preset in a
69
+ * workspace, typically. Such a file legitimately never mentions vitest-native, and
70
+ * reporting it as unconfigured is a false alarm on a working project.
71
+ */
72
+ function extendsSharedConfig(source) {
73
+ const code = withoutComments(source);
74
+ const imports = [...code.matchAll(/import\s+([^;]+?)\s+from\s*["']([^"'.][^"']*)["']/g)];
75
+ for (const [, clause, specifier] of imports) {
76
+ if (specifier === "vitest" || specifier.startsWith("vitest/")) continue;
77
+ const bindings = [...clause.matchAll(/([A-Za-z_$][\w$]*)/g)].map((m) => m[1]);
78
+ for (const binding of bindings) {
79
+ if (binding === "defineConfig" || binding === "default") continue;
80
+ if (new RegExp(`export\\s+default\\s+${binding}\\s*;?\\s*$`, "m").test(code)) return true;
81
+ if (new RegExp(`\\bmergeConfig\\s*\\(\\s*${binding}\\b`).test(code)) return true;
82
+ }
83
+ }
84
+ return false;
85
+ }
86
+ /**
87
+ * Whether a config genuinely uses the plugin.
88
+ *
89
+ * This was a substring test — `content.includes("vitest-native")` — so a config
90
+ * whose only mention was a `// TODO: migrate to vitest-native` comment reported
91
+ * "uses vitest-native" and "No blocking problems found", on a project where every
92
+ * React Native import would fail. Diagnosing that is the entire job of this
93
+ * command.
94
+ *
95
+ * The binding name is read from the import rather than assumed, so an aliased
96
+ * import still counts as used; when the import shape is not one of the forms
97
+ * below, the import alone is accepted rather than risking a false alarm on a
98
+ * working project.
99
+ */
100
+ function analyzeConfigUsage(source) {
101
+ const code = withoutComments(source);
102
+ const named = /import\s*\{([^}]*)\}\s*from\s*["']vitest-native["']/.exec(code);
103
+ const namespaced = /import\s*\*\s*as\s*([A-Za-z_$][\w$]*)\s*from\s*["']vitest-native["']/.exec(code);
104
+ const required = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*["']vitest-native["']\s*\)/.exec(code);
105
+ const bindingFrom = (clause) => {
106
+ const entry = /\breactNative\b(?:\s*(?::|as)\s*([A-Za-z_$][\w$]*))?/.exec(clause);
107
+ return entry ? entry[1] ?? "reactNative" : null;
108
+ };
109
+ if (named || required) {
110
+ const binding = bindingFrom((named ?? required)[1]);
111
+ if (!binding) return {
112
+ imports: true,
113
+ invokes: true
114
+ };
115
+ return {
116
+ imports: true,
117
+ invokes: new RegExp(`\\b${binding}\\s*\\(`).test(code)
118
+ };
119
+ }
120
+ if (namespaced) return {
121
+ imports: true,
122
+ invokes: new RegExp(`\\b${namespaced[1]}\\.\\w+\\s*\\(`).test(code)
123
+ };
124
+ if (/from\s*["']vitest-native["']|require\(\s*["']vitest-native["']\s*\)/.test(code)) return {
125
+ imports: true,
126
+ invokes: true
127
+ };
128
+ return {
129
+ imports: false,
130
+ invokes: false
131
+ };
132
+ }
133
+ /**
134
+ * The directory a test run would actually resolve from.
135
+ *
136
+ * `doctor` resolved peers from its own working directory. In a workspace that is
137
+ * frequently not where the Vitest config lives, and under pnpm a package's
138
+ * node_modules holds only its DECLARED dependencies — so a hoisted
139
+ * `@react-native/babel-preset` does not resolve from the package even though the
140
+ * real run finds it. The result was `doctor` reporting "engine 'auto' resolves to
141
+ * MOCK" for a project whose run banner said native.
142
+ *
143
+ * This is a FALLBACK, not a replacement. Node resolution walks upward, so the
144
+ * directory the command was invoked in already sees its own dependencies AND
145
+ * everything declared above it — resolving from higher up can only see less. Using
146
+ * the config root unconditionally lost dependencies a package declared itself, and
147
+ * reported a missing peer for a project that had one: the inverse of the bug this
148
+ * was written for.
149
+ *
150
+ * So the invocation directory is tried first, and this is consulted only when
151
+ * something fails to resolve there — which is the case where the command was run
152
+ * above the package that declares it.
153
+ */
154
+ function resolutionRoot(start, exists = fs.existsSync) {
155
+ let dir = start;
156
+ for (;;) {
157
+ if (CONFIG_FILES.some((name) => exists(path.join(dir, name))) && exists(path.join(dir, "package.json"))) return dir;
158
+ if (exists(path.join(dir, ".git"))) return start;
159
+ const parent = path.dirname(dir);
160
+ if (parent === dir) return start;
161
+ dir = parent;
162
+ }
163
+ }
31
164
  function runDoctor(root, nodeVersion = process.versions.node) {
32
165
  const lines = [];
33
166
  let ok = true;
@@ -37,29 +170,42 @@ function runDoctor(root, nodeVersion = process.versions.node) {
37
170
  ok = false;
38
171
  lines.push(` ✗ ${s}`);
39
172
  };
173
+ const configRoot = resolutionRoot(root);
174
+ const resolvesHere = (name) => packageVersion(root, name) !== null;
175
+ const rootFor = (name) => resolvesHere(name) || configRoot === root ? root : configRoot;
40
176
  lines.push(`vitest-native doctor — ${root}`);
41
177
  lines.push("", "Runtime");
42
178
  const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
43
- if (nodeMajorMinor[0] >= 20) pass(`Node ${nodeVersion} (floor: 20)`);
44
- else fail(`Node ${nodeVersion} — vitest-native requires Node >= 20.`);
179
+ const [floorMajor, floorMinor] = nodeFloor();
180
+ const floorText = `${floorMajor}.${floorMinor}`;
181
+ if (nodeMajorMinor[0] > floorMajor || nodeMajorMinor[0] === floorMajor && nodeMajorMinor[1] >= floorMinor) pass(`Node ${nodeVersion} (floor: ${floorText})`);
182
+ else fail(`Node ${nodeVersion} — vitest-native requires Node >= ${floorText}.`);
45
183
  lines.push("", "Peer dependencies");
46
- for (const { name, minimum, maximumMajor, minimumByMajor } of PEER_REQUIREMENTS) {
47
- const error = validatePeerDependency(name, minimum, root, maximumMajor, minimumByMajor);
184
+ for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
185
+ if (optional) continue;
186
+ const from = rootFor(name);
187
+ const error = validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor);
48
188
  if (error) fail(error);
49
- else pass(`${name} ${packageVersion(root, name)}`);
189
+ else {
190
+ pass(`${name} ${packageVersion(from, name)}`);
191
+ if (from !== root) lines.push(` (resolved from ${from}, not from here)`);
192
+ }
50
193
  }
51
194
  lines.push("", "Engine");
52
- const rnVersion = packageVersion(root, "react-native");
53
- if (detectEngine("auto", root).engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with @react-native/babel-preset + @babel/core present.`);
195
+ const rnVersion = packageVersion(rootFor("react-native"), "react-native");
196
+ if (detectEngine("auto", rootFor("@react-native/babel-preset")).engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with @react-native/babel-preset + @babel/core present.`);
54
197
  else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but @react-native/babel-preset and/or @babel/core do not resolve. Install both as devDependencies to run the real-RN native engine.`);
55
198
  else warn("engine 'auto' resolves to MOCK: react-native is not installed. That is fine for pure-logic suites; install react-native (+ its babel preset) for the native engine.");
56
199
  lines.push("", "Testing library");
57
- const rntl = packageVersion(root, "@testing-library/react-native");
200
+ const rntl = packageVersion(rootFor("@testing-library/react-native"), "@testing-library/react-native");
58
201
  if (!rntl) warn("@testing-library/react-native not found — optional, but required for render()/screen queries.");
59
202
  else {
60
203
  const rntlMajor = Number(rntl.split(".")[0]);
61
- if (rntlMajor < 12 || rntlMajor >= 15) fail(`@testing-library/react-native ${rntl} — supported range is >=12 <15.`);
204
+ const rntlReq = PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
205
+ const rntlError = rntlReq && validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
206
+ if (rntlError) warn(rntlError);
62
207
  else if (rntlMajor >= 14 && (nodeMajorMinor[0] < 22 || nodeMajorMinor[0] === 22 && nodeMajorMinor[1] < 13)) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
208
+ else if (rntlMajor >= 14 && !packageVersion(rootFor("test-renderer"), "test-renderer")) fail(`@testing-library/react-native ${rntl} requires the 'test-renderer' package, which is not installed. Every render() will fail with "Cannot find module 'test-renderer'". Install it:\n\n npm install -D test-renderer\n`);
63
209
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
64
210
  }
65
211
  lines.push("", "Auto-detected presets");
@@ -71,18 +217,21 @@ function runDoctor(root, nodeVersion = process.versions.node) {
71
217
  } catch {}
72
218
  if (detected.length) for (const d of detected) pass(d);
73
219
  else lines.push(" (none — no preset-covered packages installed)");
74
- const expo = packageVersion(root, "expo");
220
+ const expo = packageVersion(rootFor("expo"), "expo");
75
221
  if (expo) {
76
222
  lines.push("", "Expo");
77
223
  warn(`expo ${expo} detected. Expo-module components work via the auto-detected preset; suites that import Expo CORE internals (expo-router setups, dev-client wiring) can hit known limits — see the Jest migration guide's Expo notes.`);
78
224
  }
79
225
  lines.push("", "Config");
80
- const configFile = findConfigFile(root);
226
+ const configFile = findConfigFile(configRoot);
81
227
  if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
82
228
  else {
83
- const content = fs.readFileSync(path.join(root, configFile), "utf8");
84
- if (content.includes("vitest-native") || content.includes("reactNative(")) pass(`${configFile} uses vitest-native.`);
85
- else warn(`${configFile} exists but does not reference vitest-native.`);
229
+ const content = fs.readFileSync(path.join(configRoot, configFile), "utf8");
230
+ const usage = analyzeConfigUsage(content);
231
+ if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
232
+ else if (usage.imports) warn(`${configFile} imports vitest-native but never calls reactNative() — the plugin is not in \`plugins: [...]\`, so React Native imports will not resolve.`);
233
+ else if (extendsSharedConfig(content)) lines.push(` · ${configFile} builds on a shared config, so this cannot tell from here whether the plugin is wired up. Check the config it extends.`);
234
+ else warn(`${configFile} exists but does not import vitest-native` + (content.includes("vitest-native") ? " (it is only mentioned in a comment)" : "") + " — add `reactNative()` to `plugins: [...]`, or run `vitest-native init`.");
86
235
  }
87
236
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
88
237
  return {
@@ -115,8 +264,9 @@ import { reactNative } from 'vitest-native'
115
264
  import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
116
265
 
117
266
  export default defineConfig({
118
- // jestMockTransform() must come AFTER reactNative() and stay normal-order:
119
- // it rewrites top-level jest.mock(...) into hoisted vi.mock(...).
267
+ // jestMockTransform() rewrites top-level jest.mock(...) into hoisted vi.mock(...).
268
+ // Leave it without an \`enforce\`: it has to run after Vite strips TS/JSX and before
269
+ // Vitest's own mock hoister. Its position relative to reactNative() does not matter.
120
270
  plugins: [reactNative(), jestMockTransform()],
121
271
  resolve: {
122
272
  dedupe: ['react', 'react-test-renderer', 'react-is'],
@@ -278,7 +428,11 @@ function analyzeJestConfig(root) {
278
428
  const files = take(key);
279
429
  if (!files?.length) continue;
280
430
  for (const f of files) if (/react-native\/jest\/setup|jest-expo/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
281
- else {
431
+ else if (f.startsWith("<rootDir>")) {
432
+ setupFiles.push(`fileURLToPath(new URL(${JSON.stringify(f.replace(/^<rootDir>\/?/, "./"))}, import.meta.url))`);
433
+ needsUrlImport = true;
434
+ automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
435
+ } else {
282
436
  setupFiles.push(JSON.stringify(f));
283
437
  automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
284
438
  }