vitest-native 0.9.0 → 0.10.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 (53) hide show
  1. package/CHANGELOG.md +731 -0
  2. package/README.md +32 -1
  3. package/dist/cli.cjs +163 -27
  4. package/dist/cli.mjs +162 -26
  5. package/dist/{ecosystem-EFtHnKS9.mjs → ecosystem-CO5vqExO.mjs} +77 -15
  6. package/dist/{ecosystem-BIWaVwYL.cjs → ecosystem-IuZ-Gv0R.cjs} +78 -16
  7. package/dist/errors-Dm5yLNTF.mjs +64 -0
  8. package/dist/errors-flXDIeWk.cjs +75 -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-BJL4cQ-l.d.cts} +9 -4
  16. package/dist/{index-j-0tueBr.d.mts → index-CvCU0cLl.d.mts} +9 -4
  17. package/dist/index.d.mts +8 -6
  18. package/dist/index.mjs +245 -59
  19. package/dist/jest-compat/interop.mjs +15 -0
  20. package/dist/jest-compat/setup.mjs +102 -7
  21. package/dist/matchers.cjs +16 -7
  22. package/dist/matchers.mjs +16 -7
  23. package/dist/native/hooks.mjs +75 -1
  24. package/dist/native/loader.mjs +26 -6
  25. package/dist/native/module-reset.mjs +63 -0
  26. package/dist/native/registry.mjs +80 -11
  27. package/dist/native/resolve.d.mts +22 -0
  28. package/dist/native/resolve.mjs +21 -13
  29. package/dist/native/runner.mjs +21 -0
  30. package/dist/native/setup.mjs +4 -2
  31. package/dist/native/transform.mjs +108 -3
  32. package/dist/native/worker.mjs +59 -16
  33. package/dist/{pool-CJmjRgsB.mjs → pool-Bcxp4Qrg.mjs} +2 -1
  34. package/dist/{pool-DzsEo9vv.cjs → pool-CFND7plG.cjs} +2 -1
  35. package/dist/{preset-map-CNsZKfvu.mjs → preset-map-BpDG_D5m.mjs} +0 -1
  36. package/dist/{preset-map-CG4FMtsl.cjs → preset-map-DxilQ4pI.cjs} +0 -1
  37. package/dist/{presets-C4faM3ds.cjs → presets-BGTqVH6C.cjs} +94 -50
  38. package/dist/{presets-CuDrNA_W.mjs → presets-CK85x8ey.mjs} +94 -50
  39. package/dist/presets.d.mts +1 -1
  40. package/dist/presets.mjs +1 -1
  41. package/dist/rntl-matchers.d.ts +35 -0
  42. package/dist/serializer.cjs +33 -3
  43. package/dist/serializer.mjs +33 -3
  44. package/dist/setup.mjs +234 -71
  45. package/docs/release-readiness.md +22 -5
  46. package/docs/versioning.md +133 -0
  47. package/package.json +25 -35
  48. package/dist/index.cjs +0 -788
  49. package/dist/index.d.cts +0 -14
  50. package/dist/presets.cjs +0 -18
  51. package/dist/presets.d.cts +0 -2
  52. package/dist/setup.cjs +0 -2702
  53. package/dist/setup.d.cts +0 -1
package/README.md CHANGED
@@ -634,6 +634,33 @@ When supported `@testing-library/react-native` 12–14 is installed, `vitest-nat
634
634
  auto-registers its custom matchers across each major's export layout. No manual
635
635
  `extend(matchers)` call or setup file is needed.
636
636
 
637
+ ### TypeScript
638
+
639
+ The matchers run without any setup, but their **types** need one line. RNTL declares
640
+ them only for Jest — it augments the global `jest` namespace and `@jest/expect`, and
641
+ neither reaches Vitest's `Assertion` — so without this they are
642
+ `Property 'toHaveTextContent' does not exist on type 'Assertion<...>'` even though the
643
+ assertion works at runtime.
644
+
645
+ Reference the types once, anywhere in the project:
646
+
647
+ ```ts
648
+ /// <reference types="vitest-native/rntl-matchers" />
649
+ ```
650
+
651
+ or add it to `compilerOptions.types` in `tsconfig.json`:
652
+
653
+ ```json
654
+ { "compilerOptions": { "types": ["vitest-native/rntl-matchers"] } }
655
+ ```
656
+
657
+ It is opt-in rather than automatic because `@testing-library/react-native` is an
658
+ optional peer: a type import of an absent package is invisible under
659
+ `skipLibCheck: true` (React Native's default) but reports `TS2307` under
660
+ `skipLibCheck: false`, which would break projects that use the mock engine without
661
+ RNTL. Referencing nothing loads nothing — the file is not part of the program unless
662
+ asked for.
663
+
637
664
  The following matchers become available on `expect()`:
638
665
 
639
666
  | Matcher | Description |
@@ -855,6 +882,10 @@ Every release must pass:
855
882
  Current React Native edge releases are also tested weekly. See
856
883
  [the release-readiness policy](docs/release-readiness.md) for the exact gates and stability labels.
857
884
 
885
+ For what is *promised* rather than what is tested — which exports and options are protected by
886
+ semver, which are experimental, how the version ranges above may move, and what 1.0 will mean —
887
+ see [versioning and stability](docs/versioning.md).
888
+
858
889
  ---
859
890
 
860
891
  ## Requirements
@@ -864,7 +895,7 @@ Current React Native edge releases are also tested weekly. See
864
895
  | `react` | >= 18; use RN's matching React version |
865
896
  | `vite` | ^6.4.2, ^7.3.2, or ^8.0.5 |
866
897
  | `vitest` | 4.x |
867
- | `node` | >= 20; RN/RNTL may impose a higher floor |
898
+ | `node` | >= 20.19; RN/RNTL may impose a higher floor |
868
899
  | `react-native` (native engine) | 0.81–0.86 validated |
869
900
  | `@react-native/babel-preset` (native engine) | Match the installed React Native minor |
870
901
  | `@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
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);
4
+ const require_ecosystem = require("./ecosystem-IuZ-Gv0R.cjs");
5
+ const require_preset_map = require("./preset-map-DxilQ4pI.cjs");
8
6
  let node_fs = require("node:fs");
9
7
  node_fs = require_chunk.__toESM(node_fs, 1);
8
+ let node_path = require("node:path");
9
+ node_path = require_chunk.__toESM(node_path, 1);
10
10
  let node_module = require("node:module");
11
11
  //#region src/cli/doctor.ts
12
12
  /**
@@ -21,17 +21,135 @@ function packageVersion(root, name) {
21
21
  return null;
22
22
  }
23
23
  }
24
+ /**
25
+ * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
26
+ * is used when there is none.
27
+ *
28
+ * The vite.config entries were missing, so a correct setup that configures Vitest
29
+ * from vite.config.ts — normal in projects that already had Vite — was told "no
30
+ * vitest.config.* found — run `vitest-native init`". Following that produces a
31
+ * second config which then TAKES PRECEDENCE over the working one, so the advice
32
+ * did not just misreport, it would have broken the project.
33
+ */
34
+ const CONFIG_FILES = [
35
+ "vitest.config.ts",
36
+ "vitest.config.mts",
37
+ "vitest.config.js",
38
+ "vitest.config.mjs",
39
+ "vitest.config.cts",
40
+ "vitest.config.cjs",
41
+ "vite.config.ts",
42
+ "vite.config.mts",
43
+ "vite.config.js",
44
+ "vite.config.mjs",
45
+ "vite.config.cts",
46
+ "vite.config.cjs"
47
+ ];
24
48
  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;
49
+ for (const name of CONFIG_FILES) if (node_fs.default.existsSync(node_path.default.join(root, name))) return name;
33
50
  return null;
34
51
  }
52
+ /** Source with comments removed, so a mention inside one cannot be mistaken for use. */
53
+ function withoutComments(source) {
54
+ return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
55
+ }
56
+ /**
57
+ * Whether a config is built on one imported from elsewhere — a shared preset in a
58
+ * workspace, typically. Such a file legitimately never mentions vitest-native, and
59
+ * reporting it as unconfigured is a false alarm on a working project.
60
+ */
61
+ function extendsSharedConfig(source) {
62
+ const code = withoutComments(source);
63
+ const imports = [...code.matchAll(/import\s+([^;]+?)\s+from\s*["']([^"'.][^"']*)["']/g)];
64
+ for (const [, clause, specifier] of imports) {
65
+ if (specifier === "vitest" || specifier.startsWith("vitest/")) continue;
66
+ const bindings = [...clause.matchAll(/([A-Za-z_$][\w$]*)/g)].map((m) => m[1]);
67
+ for (const binding of bindings) {
68
+ if (binding === "defineConfig" || binding === "default") continue;
69
+ if (new RegExp(`export\\s+default\\s+${binding}\\s*;?\\s*$`, "m").test(code)) return true;
70
+ if (new RegExp(`\\bmergeConfig\\s*\\(\\s*${binding}\\b`).test(code)) return true;
71
+ }
72
+ }
73
+ return false;
74
+ }
75
+ /**
76
+ * Whether a config genuinely uses the plugin.
77
+ *
78
+ * This was a substring test — `content.includes("vitest-native")` — so a config
79
+ * whose only mention was a `// TODO: migrate to vitest-native` comment reported
80
+ * "uses vitest-native" and "No blocking problems found", on a project where every
81
+ * React Native import would fail. Diagnosing that is the entire job of this
82
+ * command.
83
+ *
84
+ * The binding name is read from the import rather than assumed, so an aliased
85
+ * import still counts as used; when the import shape is not one of the forms
86
+ * below, the import alone is accepted rather than risking a false alarm on a
87
+ * working project.
88
+ */
89
+ function analyzeConfigUsage(source) {
90
+ const code = withoutComments(source);
91
+ const named = /import\s*\{([^}]*)\}\s*from\s*["']vitest-native["']/.exec(code);
92
+ const namespaced = /import\s*\*\s*as\s*([A-Za-z_$][\w$]*)\s*from\s*["']vitest-native["']/.exec(code);
93
+ const required = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*["']vitest-native["']\s*\)/.exec(code);
94
+ const bindingFrom = (clause) => {
95
+ const entry = /\breactNative\b(?:\s*(?::|as)\s*([A-Za-z_$][\w$]*))?/.exec(clause);
96
+ return entry ? entry[1] ?? "reactNative" : null;
97
+ };
98
+ if (named || required) {
99
+ const binding = bindingFrom((named ?? required)[1]);
100
+ if (!binding) return {
101
+ imports: true,
102
+ invokes: true
103
+ };
104
+ return {
105
+ imports: true,
106
+ invokes: new RegExp(`\\b${binding}\\s*\\(`).test(code)
107
+ };
108
+ }
109
+ if (namespaced) return {
110
+ imports: true,
111
+ invokes: new RegExp(`\\b${namespaced[1]}\\.\\w+\\s*\\(`).test(code)
112
+ };
113
+ if (/from\s*["']vitest-native["']|require\(\s*["']vitest-native["']\s*\)/.test(code)) return {
114
+ imports: true,
115
+ invokes: true
116
+ };
117
+ return {
118
+ imports: false,
119
+ invokes: false
120
+ };
121
+ }
122
+ /**
123
+ * The directory a test run would actually resolve from.
124
+ *
125
+ * `doctor` resolved peers from its own working directory. In a workspace that is
126
+ * frequently not where the Vitest config lives, and under pnpm a package's
127
+ * node_modules holds only its DECLARED dependencies — so a hoisted
128
+ * `@react-native/babel-preset` does not resolve from the package even though the
129
+ * real run finds it. The result was `doctor` reporting "engine 'auto' resolves to
130
+ * MOCK" for a project whose run banner said native.
131
+ *
132
+ * This is a FALLBACK, not a replacement. Node resolution walks upward, so the
133
+ * directory the command was invoked in already sees its own dependencies AND
134
+ * everything declared above it — resolving from higher up can only see less. Using
135
+ * the config root unconditionally lost dependencies a package declared itself, and
136
+ * reported a missing peer for a project that had one: the inverse of the bug this
137
+ * was written for.
138
+ *
139
+ * So the invocation directory is tried first, and this is consulted only when
140
+ * something fails to resolve there — which is the case where the command was run
141
+ * above the package that declares it.
142
+ */
143
+ function resolutionRoot(start, exists = node_fs.default.existsSync) {
144
+ let dir = start;
145
+ for (;;) {
146
+ if (CONFIG_FILES.some((name) => exists(node_path.default.join(dir, name))) && exists(node_path.default.join(dir, "package.json"))) return dir;
147
+ if (exists(node_path.default.join(dir, ".git"))) return start;
148
+ const parent = node_path.default.dirname(dir);
149
+ if (parent === dir) return start;
150
+ dir = parent;
151
+ }
152
+ }
35
153
  function runDoctor(root, nodeVersion = process.versions.node) {
36
154
  const lines = [];
37
155
  let ok = true;
@@ -41,28 +159,38 @@ function runDoctor(root, nodeVersion = process.versions.node) {
41
159
  ok = false;
42
160
  lines.push(` ✗ ${s}`);
43
161
  };
162
+ const configRoot = resolutionRoot(root);
163
+ const resolvesHere = (name) => packageVersion(root, name) !== null;
164
+ const rootFor = (name) => resolvesHere(name) || configRoot === root ? root : configRoot;
44
165
  lines.push(`vitest-native doctor — ${root}`);
45
166
  lines.push("", "Runtime");
46
167
  const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
47
168
  if (nodeMajorMinor[0] >= 20) pass(`Node ${nodeVersion} (floor: 20)`);
48
169
  else fail(`Node ${nodeVersion} — vitest-native requires Node >= 20.`);
49
170
  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);
171
+ for (const { name, minimum, maximumMajor, minimumByMajor, optional } of require_ecosystem.PEER_REQUIREMENTS) {
172
+ if (optional) continue;
173
+ const from = rootFor(name);
174
+ const error = require_ecosystem.validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor);
52
175
  if (error) fail(error);
53
- else pass(`${name} ${packageVersion(root, name)}`);
176
+ else {
177
+ pass(`${name} ${packageVersion(from, name)}`);
178
+ if (from !== root) lines.push(` (resolved from ${from}, not from here)`);
179
+ }
54
180
  }
55
181
  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.`);
182
+ const rnVersion = packageVersion(rootFor("react-native"), "react-native");
183
+ 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
184
  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
185
  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
186
  lines.push("", "Testing library");
61
- const rntl = packageVersion(root, "@testing-library/react-native");
187
+ const rntl = packageVersion(rootFor("@testing-library/react-native"), "@testing-library/react-native");
62
188
  if (!rntl) warn("@testing-library/react-native not found — optional, but required for render()/screen queries.");
63
189
  else {
64
190
  const rntlMajor = Number(rntl.split(".")[0]);
65
- if (rntlMajor < 12 || rntlMajor >= 15) fail(`@testing-library/react-native ${rntl} — supported range is >=12 <15.`);
191
+ const rntlReq = require_ecosystem.PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
192
+ const rntlError = rntlReq && require_ecosystem.validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
193
+ if (rntlError) warn(rntlError);
66
194
  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.`);
67
195
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
68
196
  }
@@ -75,18 +203,21 @@ function runDoctor(root, nodeVersion = process.versions.node) {
75
203
  } catch {}
76
204
  if (detected.length) for (const d of detected) pass(d);
77
205
  else lines.push(" (none — no preset-covered packages installed)");
78
- const expo = packageVersion(root, "expo");
206
+ const expo = packageVersion(rootFor("expo"), "expo");
79
207
  if (expo) {
80
208
  lines.push("", "Expo");
81
209
  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
210
  }
83
211
  lines.push("", "Config");
84
- const configFile = findConfigFile(root);
212
+ const configFile = findConfigFile(configRoot);
85
213
  if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
86
214
  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.`);
215
+ const content = node_fs.default.readFileSync(node_path.default.join(configRoot, configFile), "utf8");
216
+ const usage = analyzeConfigUsage(content);
217
+ if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
218
+ 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.`);
219
+ 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.`);
220
+ 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
221
  }
91
222
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
92
223
  return {
@@ -119,8 +250,9 @@ import { reactNative } from 'vitest-native'
119
250
  import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
120
251
 
121
252
  export default defineConfig({
122
- // jestMockTransform() must come AFTER reactNative() and stay normal-order:
123
- // it rewrites top-level jest.mock(...) into hoisted vi.mock(...).
253
+ // jestMockTransform() rewrites top-level jest.mock(...) into hoisted vi.mock(...).
254
+ // Leave it without an \`enforce\`: it has to run after Vite strips TS/JSX and before
255
+ // Vitest's own mock hoister. Its position relative to reactNative() does not matter.
124
256
  plugins: [reactNative(), jestMockTransform()],
125
257
  resolve: {
126
258
  dedupe: ['react', 'react-test-renderer', 'react-is'],
@@ -282,7 +414,11 @@ function analyzeJestConfig(root) {
282
414
  const files = take(key);
283
415
  if (!files?.length) continue;
284
416
  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 {
417
+ else if (f.startsWith("<rootDir>")) {
418
+ setupFiles.push(`fileURLToPath(new URL(${JSON.stringify(f.replace(/^<rootDir>\/?/, "./"))}, import.meta.url))`);
419
+ needsUrlImport = true;
420
+ automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
421
+ } else {
286
422
  setupFiles.push(JSON.stringify(f));
287
423
  automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
288
424
  }
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 { a as validatePeerDependency, n as detectEngine, r as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-CO5vqExO.mjs";
3
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-BpDG_D5m.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,135 @@ function packageVersion(root, name) {
17
17
  return null;
18
18
  }
19
19
  }
20
+ /**
21
+ * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
22
+ * is used when there is none.
23
+ *
24
+ * The vite.config entries were missing, so a correct setup that configures Vitest
25
+ * from vite.config.ts — normal in projects that already had Vite — was told "no
26
+ * vitest.config.* found — run `vitest-native init`". Following that produces a
27
+ * second config which then TAKES PRECEDENCE over the working one, so the advice
28
+ * did not just misreport, it would have broken the project.
29
+ */
30
+ const CONFIG_FILES = [
31
+ "vitest.config.ts",
32
+ "vitest.config.mts",
33
+ "vitest.config.js",
34
+ "vitest.config.mjs",
35
+ "vitest.config.cts",
36
+ "vitest.config.cjs",
37
+ "vite.config.ts",
38
+ "vite.config.mts",
39
+ "vite.config.js",
40
+ "vite.config.mjs",
41
+ "vite.config.cts",
42
+ "vite.config.cjs"
43
+ ];
20
44
  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;
45
+ for (const name of CONFIG_FILES) if (fs.existsSync(path.join(root, name))) return name;
29
46
  return null;
30
47
  }
48
+ /** Source with comments removed, so a mention inside one cannot be mistaken for use. */
49
+ function withoutComments(source) {
50
+ return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
51
+ }
52
+ /**
53
+ * Whether a config is built on one imported from elsewhere — a shared preset in a
54
+ * workspace, typically. Such a file legitimately never mentions vitest-native, and
55
+ * reporting it as unconfigured is a false alarm on a working project.
56
+ */
57
+ function extendsSharedConfig(source) {
58
+ const code = withoutComments(source);
59
+ const imports = [...code.matchAll(/import\s+([^;]+?)\s+from\s*["']([^"'.][^"']*)["']/g)];
60
+ for (const [, clause, specifier] of imports) {
61
+ if (specifier === "vitest" || specifier.startsWith("vitest/")) continue;
62
+ const bindings = [...clause.matchAll(/([A-Za-z_$][\w$]*)/g)].map((m) => m[1]);
63
+ for (const binding of bindings) {
64
+ if (binding === "defineConfig" || binding === "default") continue;
65
+ if (new RegExp(`export\\s+default\\s+${binding}\\s*;?\\s*$`, "m").test(code)) return true;
66
+ if (new RegExp(`\\bmergeConfig\\s*\\(\\s*${binding}\\b`).test(code)) return true;
67
+ }
68
+ }
69
+ return false;
70
+ }
71
+ /**
72
+ * Whether a config genuinely uses the plugin.
73
+ *
74
+ * This was a substring test — `content.includes("vitest-native")` — so a config
75
+ * whose only mention was a `// TODO: migrate to vitest-native` comment reported
76
+ * "uses vitest-native" and "No blocking problems found", on a project where every
77
+ * React Native import would fail. Diagnosing that is the entire job of this
78
+ * command.
79
+ *
80
+ * The binding name is read from the import rather than assumed, so an aliased
81
+ * import still counts as used; when the import shape is not one of the forms
82
+ * below, the import alone is accepted rather than risking a false alarm on a
83
+ * working project.
84
+ */
85
+ function analyzeConfigUsage(source) {
86
+ const code = withoutComments(source);
87
+ const named = /import\s*\{([^}]*)\}\s*from\s*["']vitest-native["']/.exec(code);
88
+ const namespaced = /import\s*\*\s*as\s*([A-Za-z_$][\w$]*)\s*from\s*["']vitest-native["']/.exec(code);
89
+ const required = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*["']vitest-native["']\s*\)/.exec(code);
90
+ const bindingFrom = (clause) => {
91
+ const entry = /\breactNative\b(?:\s*(?::|as)\s*([A-Za-z_$][\w$]*))?/.exec(clause);
92
+ return entry ? entry[1] ?? "reactNative" : null;
93
+ };
94
+ if (named || required) {
95
+ const binding = bindingFrom((named ?? required)[1]);
96
+ if (!binding) return {
97
+ imports: true,
98
+ invokes: true
99
+ };
100
+ return {
101
+ imports: true,
102
+ invokes: new RegExp(`\\b${binding}\\s*\\(`).test(code)
103
+ };
104
+ }
105
+ if (namespaced) return {
106
+ imports: true,
107
+ invokes: new RegExp(`\\b${namespaced[1]}\\.\\w+\\s*\\(`).test(code)
108
+ };
109
+ if (/from\s*["']vitest-native["']|require\(\s*["']vitest-native["']\s*\)/.test(code)) return {
110
+ imports: true,
111
+ invokes: true
112
+ };
113
+ return {
114
+ imports: false,
115
+ invokes: false
116
+ };
117
+ }
118
+ /**
119
+ * The directory a test run would actually resolve from.
120
+ *
121
+ * `doctor` resolved peers from its own working directory. In a workspace that is
122
+ * frequently not where the Vitest config lives, and under pnpm a package's
123
+ * node_modules holds only its DECLARED dependencies — so a hoisted
124
+ * `@react-native/babel-preset` does not resolve from the package even though the
125
+ * real run finds it. The result was `doctor` reporting "engine 'auto' resolves to
126
+ * MOCK" for a project whose run banner said native.
127
+ *
128
+ * This is a FALLBACK, not a replacement. Node resolution walks upward, so the
129
+ * directory the command was invoked in already sees its own dependencies AND
130
+ * everything declared above it — resolving from higher up can only see less. Using
131
+ * the config root unconditionally lost dependencies a package declared itself, and
132
+ * reported a missing peer for a project that had one: the inverse of the bug this
133
+ * was written for.
134
+ *
135
+ * So the invocation directory is tried first, and this is consulted only when
136
+ * something fails to resolve there — which is the case where the command was run
137
+ * above the package that declares it.
138
+ */
139
+ function resolutionRoot(start, exists = fs.existsSync) {
140
+ let dir = start;
141
+ for (;;) {
142
+ if (CONFIG_FILES.some((name) => exists(path.join(dir, name))) && exists(path.join(dir, "package.json"))) return dir;
143
+ if (exists(path.join(dir, ".git"))) return start;
144
+ const parent = path.dirname(dir);
145
+ if (parent === dir) return start;
146
+ dir = parent;
147
+ }
148
+ }
31
149
  function runDoctor(root, nodeVersion = process.versions.node) {
32
150
  const lines = [];
33
151
  let ok = true;
@@ -37,28 +155,38 @@ function runDoctor(root, nodeVersion = process.versions.node) {
37
155
  ok = false;
38
156
  lines.push(` ✗ ${s}`);
39
157
  };
158
+ const configRoot = resolutionRoot(root);
159
+ const resolvesHere = (name) => packageVersion(root, name) !== null;
160
+ const rootFor = (name) => resolvesHere(name) || configRoot === root ? root : configRoot;
40
161
  lines.push(`vitest-native doctor — ${root}`);
41
162
  lines.push("", "Runtime");
42
163
  const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
43
164
  if (nodeMajorMinor[0] >= 20) pass(`Node ${nodeVersion} (floor: 20)`);
44
165
  else fail(`Node ${nodeVersion} — vitest-native requires Node >= 20.`);
45
166
  lines.push("", "Peer dependencies");
46
- for (const { name, minimum, maximumMajor, minimumByMajor } of PEER_REQUIREMENTS) {
47
- const error = validatePeerDependency(name, minimum, root, maximumMajor, minimumByMajor);
167
+ for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
168
+ if (optional) continue;
169
+ const from = rootFor(name);
170
+ const error = validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor);
48
171
  if (error) fail(error);
49
- else pass(`${name} ${packageVersion(root, name)}`);
172
+ else {
173
+ pass(`${name} ${packageVersion(from, name)}`);
174
+ if (from !== root) lines.push(` (resolved from ${from}, not from here)`);
175
+ }
50
176
  }
51
177
  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.`);
178
+ const rnVersion = packageVersion(rootFor("react-native"), "react-native");
179
+ 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
180
  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
181
  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
182
  lines.push("", "Testing library");
57
- const rntl = packageVersion(root, "@testing-library/react-native");
183
+ const rntl = packageVersion(rootFor("@testing-library/react-native"), "@testing-library/react-native");
58
184
  if (!rntl) warn("@testing-library/react-native not found — optional, but required for render()/screen queries.");
59
185
  else {
60
186
  const rntlMajor = Number(rntl.split(".")[0]);
61
- if (rntlMajor < 12 || rntlMajor >= 15) fail(`@testing-library/react-native ${rntl} — supported range is >=12 <15.`);
187
+ const rntlReq = PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
188
+ const rntlError = rntlReq && validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
189
+ if (rntlError) warn(rntlError);
62
190
  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.`);
63
191
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
64
192
  }
@@ -71,18 +199,21 @@ function runDoctor(root, nodeVersion = process.versions.node) {
71
199
  } catch {}
72
200
  if (detected.length) for (const d of detected) pass(d);
73
201
  else lines.push(" (none — no preset-covered packages installed)");
74
- const expo = packageVersion(root, "expo");
202
+ const expo = packageVersion(rootFor("expo"), "expo");
75
203
  if (expo) {
76
204
  lines.push("", "Expo");
77
205
  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
206
  }
79
207
  lines.push("", "Config");
80
- const configFile = findConfigFile(root);
208
+ const configFile = findConfigFile(configRoot);
81
209
  if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
82
210
  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.`);
211
+ const content = fs.readFileSync(path.join(configRoot, configFile), "utf8");
212
+ const usage = analyzeConfigUsage(content);
213
+ if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
214
+ 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.`);
215
+ 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.`);
216
+ 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
217
  }
87
218
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
88
219
  return {
@@ -115,8 +246,9 @@ import { reactNative } from 'vitest-native'
115
246
  import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
116
247
 
117
248
  export default defineConfig({
118
- // jestMockTransform() must come AFTER reactNative() and stay normal-order:
119
- // it rewrites top-level jest.mock(...) into hoisted vi.mock(...).
249
+ // jestMockTransform() rewrites top-level jest.mock(...) into hoisted vi.mock(...).
250
+ // Leave it without an \`enforce\`: it has to run after Vite strips TS/JSX and before
251
+ // Vitest's own mock hoister. Its position relative to reactNative() does not matter.
120
252
  plugins: [reactNative(), jestMockTransform()],
121
253
  resolve: {
122
254
  dedupe: ['react', 'react-test-renderer', 'react-is'],
@@ -278,7 +410,11 @@ function analyzeJestConfig(root) {
278
410
  const files = take(key);
279
411
  if (!files?.length) continue;
280
412
  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 {
413
+ else if (f.startsWith("<rootDir>")) {
414
+ setupFiles.push(`fileURLToPath(new URL(${JSON.stringify(f.replace(/^<rootDir>\/?/, "./"))}, import.meta.url))`);
415
+ needsUrlImport = true;
416
+ automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
417
+ } else {
282
418
  setupFiles.push(JSON.stringify(f));
283
419
  automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
284
420
  }