vitest-native 0.14.1 → 0.15.0-rc.2

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 (89) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.d.mts +9 -1
  3. package/dist/cli.mjs +2609 -361
  4. package/dist/context.d.mts +19 -0
  5. package/dist/context.mjs +47 -1
  6. package/dist/docs-url.d.mts +4 -0
  7. package/dist/docs-url.mjs +9 -0
  8. package/dist/errors.d.mts +21 -1
  9. package/dist/hang-watch-setup.mjs +55 -0
  10. package/dist/hang-watch.d.mts +56 -0
  11. package/dist/hang-watch.mjs +343 -0
  12. package/dist/helpers.cjs +24 -53
  13. package/dist/helpers.mjs +22 -1
  14. package/dist/host-D0r3P_T1.mjs +1985 -0
  15. package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
  16. package/dist/index.d.mts +2 -1
  17. package/dist/index.mjs +723 -149
  18. package/dist/jest-compat/aliases.d.mts +1 -0
  19. package/dist/jest-compat/aliases.mjs +11 -0
  20. package/dist/jest-compat/interop.mjs +1 -1
  21. package/dist/jest-compat/jest-object.mjs +23 -5
  22. package/dist/jest-compat/node-registry.mjs +836 -68
  23. package/dist/jest-compat/setup.mjs +205 -12
  24. package/dist/jest-compat.cjs +383 -47
  25. package/dist/jest-compat.d.cts +19 -2
  26. package/dist/jest-compat.d.mts +19 -2
  27. package/dist/jest-compat.mjs +232 -47
  28. package/dist/matchers.d.cts +0 -1
  29. package/dist/matchers.d.mts +0 -1
  30. package/dist/native/assets.mjs +3 -1
  31. package/dist/native/babel-caller.d.mts +13 -0
  32. package/dist/native/babel-caller.mjs +24 -0
  33. package/dist/native/babel-toolchain.mjs +27 -3
  34. package/dist/native/boundary.mjs +45 -8
  35. package/dist/native/bounded-process.mjs +63 -5
  36. package/dist/native/bridge-client.mjs +133 -0
  37. package/dist/native/bridge-server.mjs +215 -0
  38. package/dist/native/bridge-thread.mjs +79 -0
  39. package/dist/native/bridge.mjs +512 -0
  40. package/dist/native/compile-error.mjs +120 -0
  41. package/dist/native/explain.mjs +3 -2
  42. package/dist/native/expo-module-mocks.mjs +2 -0
  43. package/dist/native/export-condition-recovery.mjs +20 -99
  44. package/dist/native/hooks.mjs +256 -133
  45. package/dist/native/jest-resolvers.mjs +94 -0
  46. package/dist/native/library-jest.mjs +352 -0
  47. package/dist/native/loader.mjs +167 -73
  48. package/dist/native/match.mjs +67 -7
  49. package/dist/native/module-reset.mjs +44 -49
  50. package/dist/native/ownership-ledger.d.mts +87 -0
  51. package/dist/native/ownership-ledger.mjs +524 -0
  52. package/dist/native/ownership.d.mts +20 -0
  53. package/dist/native/ownership.mjs +114 -0
  54. package/dist/native/registry-compiler.mjs +39 -5
  55. package/dist/native/registry-process.mjs +327 -28
  56. package/dist/native/registry.mjs +752 -200
  57. package/dist/native/resident-health.mjs +1 -0
  58. package/dist/native/resolve.d.mts +7 -0
  59. package/dist/native/resolve.mjs +119 -4
  60. package/dist/native/rntl-hooks.mjs +9 -5
  61. package/dist/native/rntl-text-host.mjs +5 -15
  62. package/dist/native/root-spelling.d.mts +6 -0
  63. package/dist/native/root-spelling.mjs +77 -0
  64. package/dist/native/runner.mjs +2 -19
  65. package/dist/native/setup.mjs +119 -38
  66. package/dist/native/shared-resolver.d.mts +141 -0
  67. package/dist/native/shared-resolver.mjs +719 -0
  68. package/dist/native/test-runner.mjs +26 -0
  69. package/dist/native/transform.mjs +18 -22
  70. package/dist/native/worker.mjs +9 -4
  71. package/dist/node-dispatch.mjs +293 -0
  72. package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
  73. package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
  74. package/dist/presets.d.mts +1 -1
  75. package/dist/presets.mjs +1 -1
  76. package/dist/rntl-matchers.d.ts +11 -15
  77. package/dist/rntl-support.mjs +28 -13
  78. package/dist/root-mocks-BNXeosbR.mjs +155 -0
  79. package/dist/serializer.cjs +7 -5
  80. package/dist/serializer.d.cts +7 -5
  81. package/dist/serializer.d.mts +7 -5
  82. package/dist/serializer.mjs +7 -5
  83. package/dist/setup.mjs +26 -27
  84. package/docs/migrating-from-jest.md +9 -232
  85. package/docs/migrating-from-vitest-react-native.md +4 -4
  86. package/docs/release-readiness.md +9 -11
  87. package/docs/versioning.md +38 -9
  88. package/package.json +59 -33
  89. package/dist/host-BAAAlSkO.mjs +0 -1028
@@ -1,5 +1,8 @@
1
+ import { n as ignorePattern, t as findNodeModuleMocks } from "./root-mocks-BNXeosbR.mjs";
2
+ import { fileURLToPath } from "node:url";
1
3
  import path from "node:path";
2
4
  import fs from "node:fs";
5
+ import { VitestNativeError } from "./errors.mjs";
3
6
  import { MagicString } from "magic-string";
4
7
  // src/jest-compat/transform.ts
5
8
  const HOISTABLE = /* @__PURE__ */ new Set([
@@ -44,23 +47,41 @@ function requireActualSpec(node) {
44
47
  if (callee?.type !== "MemberExpression" || callee.computed) return null;
45
48
  if (callee.object?.type !== "Identifier" || callee.object.name !== "jest") return null;
46
49
  if (callee.property?.type !== "Identifier" || callee.property.name !== "requireActual") return null;
47
- const arg = node.arguments[0];
48
- if (arg.type === "Literal" && typeof arg.value === "string") return arg.value;
49
- if (arg.type === "TemplateLiteral" && arg.expressions.length === 0) return arg.quasis[0].value.cooked ?? null;
50
+ return literalSpec(node.arguments[0]);
51
+ }
52
+ /** The string specifier of a `require('<literal>')` call, or null. */
53
+ function requireSpec(node) {
54
+ if (node.type !== "CallExpression" || node.arguments.length !== 1) return null;
55
+ if (node.callee?.type !== "Identifier" || node.callee.name !== "require") return null;
56
+ return literalSpec(node.arguments[0]);
57
+ }
58
+ function literalSpec(arg) {
59
+ if (arg?.type === "Literal" && typeof arg.value === "string") return arg.value;
60
+ if (arg?.type === "TemplateLiteral" && arg.expressions.length === 0) return arg.quasis[0].value.cooked ?? null;
50
61
  return null;
51
62
  }
63
+ /** Whether the file declares its own `require` (createRequire, a parameter, an import). */
64
+ const BINDS_REQUIRE = /\b(?:const|let|var|function|class)\s+require\b|\bimport\s+require\b|[(,]\s*require\s*[,)=]|\{[^}]*\brequire\b[^}]*\}\s*=/;
52
65
  /**
53
- * The `jest.requireActual` calls a factory makes while it runs: those in its own body,
54
- * not in a nested function or a class body (where `await` is not allowed either).
66
+ * The `jest.requireActual` and `require` calls a factory makes while it runs: those in
67
+ * its own body, not in a nested function or a class body (where `await` is not allowed
68
+ * either). `mocked` is the specifier the factory mocks, whose own require stays as is.
55
69
  */
56
- function ownRequireActualCalls(factory) {
70
+ function ownLoadCalls(factory, mocked, requireIsGlobal) {
57
71
  const calls = [];
58
72
  walk(factory.body, (node) => {
59
73
  if (FUNCTION.has(node.type) || node.type === "ClassBody") return false;
60
- const spec = requireActualSpec(node);
61
- if (spec !== null) calls.push({
74
+ const actual = requireActualSpec(node);
75
+ if (actual !== null) return void calls.push({
62
76
  node,
63
- spec
77
+ spec: actual,
78
+ kind: "requireActual"
79
+ });
80
+ const required = requireIsGlobal ? requireSpec(node) : null;
81
+ if (required !== null && required !== mocked) calls.push({
82
+ node,
83
+ spec: required,
84
+ kind: "require"
64
85
  });
65
86
  });
66
87
  return calls;
@@ -126,62 +147,214 @@ function isViteOwnedSource(resolved, project) {
126
147
  *
127
148
  * Opt-in: add after `reactNative()`; pair with `jestCompatSetup` + `globals: true`.
128
149
  */
129
- function jestMockTransform() {
150
+ function jestMockTransform(options = {}) {
130
151
  let project = {
131
152
  ownership: () => null,
153
+ coveredBy: () => null,
132
154
  inline: [],
133
155
  external: []
134
156
  };
157
+ const rootMockModules = /* @__PURE__ */ new Map();
158
+ const projectsByRoot = /* @__PURE__ */ new Map();
135
159
  return {
136
160
  name: "vitest-native:jest-mock-hoist",
161
+ config(userConfig) {
162
+ if (options.rootMocks === false) return;
163
+ const test = userConfig.test ??= {};
164
+ const root = path.resolve(test.root ?? userConfig.root ?? process.cwd());
165
+ const ignore = (options.modulePathIgnorePatterns ?? []).map((pattern) => {
166
+ const regex = ignorePattern(pattern, root);
167
+ if (!regex) throw new VitestNativeError("INVALID_OPTION", `jestMockTransform: modulePathIgnorePatterns entry ${JSON.stringify(pattern)} is not a valid regular expression`);
168
+ return regex;
169
+ });
170
+ const found = findNodeModuleMocks((options.roots ?? ["."]).map((r) => path.resolve(root, r)), root, ignore);
171
+ if (found.mocks.length === 0 && found.duplicates.length === 0) return;
172
+ const id = viteId(path.join(root, ROOT_MOCKS_FILE));
173
+ rootMockModules.set(id, {
174
+ root,
175
+ ...found
176
+ });
177
+ const setupFiles = Array.isArray(test.setupFiles) ? [...test.setupFiles] : test.setupFiles ? [test.setupFiles] : [];
178
+ if (setupFiles.includes(id)) return;
179
+ let compat = -1;
180
+ setupFiles.forEach((file, index) => {
181
+ if (JEST_COMPAT_SETUP.test(file)) compat = index;
182
+ });
183
+ setupFiles.splice(compat + 1, 0, id);
184
+ test.setupFiles = setupFiles;
185
+ },
137
186
  configResolved(config) {
138
187
  const native = config.plugins.find((plugin) => plugin.name === "vitest-native");
139
188
  const deps = config.test?.server?.deps;
140
189
  const list = (value) => Array.isArray(value) ? value : value == null ? [] : [value];
141
190
  project = {
142
191
  ownership: () => native?.api?.nativeOwnership?.() ?? null,
192
+ coveredBy: (spec) => native?.api?.packageCoveredBy?.(spec) ?? null,
143
193
  inline: list(deps?.inline),
144
194
  external: list(deps?.external)
145
195
  };
196
+ if (config.root) projectsByRoot.set(path.resolve(config.root), project);
197
+ },
198
+ resolveId(id) {
199
+ if (path.isAbsolute(id) && rootMockModules.has(viteId(id))) return viteId(id);
200
+ if (id !== `/${ROOT_MOCKS_FILE}`) return null;
201
+ const root = this.environment?.config?.root;
202
+ const file = root ? viteId(path.join(root, ROOT_MOCKS_FILE)) : null;
203
+ return file && rootMockModules.has(file) ? file : null;
204
+ },
205
+ load(id) {
206
+ const module = rootMockModules.get(id);
207
+ if (!module) return null;
208
+ const owner = projectsByRoot.get(module.root) ?? project;
209
+ return rootMocksSource(module, (spec) => owner.coveredBy(spec));
146
210
  },
147
211
  transform(code, id) {
148
212
  if (id.includes("/node_modules/")) return null;
149
213
  const file = id.split("?")[0];
150
214
  if (!TRANSFORMABLE.test(file)) return null;
151
215
  if (!HAS_JEST_MOCK.test(code)) return null;
152
- let ast;
153
- try {
154
- ast = this.parse(code);
155
- } catch {
156
- return null;
216
+ const owner = rootMockModules.has(file) ? projectsByRoot.get(rootMockModules.get(file).root) ?? project : project;
217
+ let module;
218
+ const spelled = path.isAbsolute(file) ? viteId(file) : file;
219
+ for (const candidate of rootMockModules.values()) {
220
+ const root = viteId(candidate.root);
221
+ if ((spelled === root || spelled.startsWith(root.endsWith("/") ? root : `${root}/`)) && (!module || candidate.root.length > module.root.length)) module = candidate;
157
222
  }
158
- const candidates = /* @__PURE__ */ new Map();
159
- walk(ast, (node) => {
160
- const factory = mockFactoryOf(node);
161
- if (!factory || factory.generator) return;
162
- const calls = ownRequireActualCalls(factory);
163
- if (calls.length > 0) candidates.set(factory, calls);
164
- });
165
- if (candidates.size === 0) return rewrite(code, ast, /* @__PURE__ */ new Map());
166
- const specs = new Set([...candidates.values()].flat().map((call) => call.spec));
167
- return Promise.all([...specs].map(async (spec) => {
168
- try {
169
- return [spec, isViteOwnedSource(await this.resolve(spec, id), project)];
170
- } catch {
171
- return [spec, false];
172
- }
173
- })).then((resolved) => {
174
- const owned = new Set(resolved.filter(([, yes]) => yes).map(([spec]) => spec));
175
- const toAsync = /* @__PURE__ */ new Map();
176
- for (const [factory, calls] of candidates) {
177
- const moved = calls.filter((call) => owned.has(call.spec)).map((call) => call.node);
178
- if (moved.length > 0) toAsync.set(factory, moved);
179
- }
180
- return rewrite(code, ast, toAsync);
181
- });
223
+ const moduleOwner = module ? projectsByRoot.get(module.root) ?? project : project;
224
+ const manualMockFor = (spec) => {
225
+ const mock = module?.mocks.find((m) => m.spec === spec);
226
+ return mock && !moduleOwner.coveredBy(spec) ? mock.file : null;
227
+ };
228
+ const finish = (adapted) => {
229
+ if (!adapted?.changed) return null;
230
+ if (adapted.usesSetup) adapted.s.prepend(SETUP_ACCESSOR);
231
+ return {
232
+ code: adapted.s.toString(),
233
+ map: adapted.s.generateMap({ hires: true })
234
+ };
235
+ };
236
+ const adapted = adapt(this, code, id, owner, manualMockFor);
237
+ return adapted instanceof Promise ? adapted.then(finish) : finish(adapted);
182
238
  }
183
239
  };
184
240
  }
241
+ /** The generated setup module's file name, in each project's root. */
242
+ const ROOT_MOCKS_FILE = "vitest-native.root-mocks.mjs";
243
+ /**
244
+ * An absolute file as Vite spells a module id and an import of it: forward slashes, on
245
+ * Windows too. The generated module is keyed by this spelling, since it exists only as an
246
+ * id, and a backslash path in an import Vite resolves is not one it finds.
247
+ */
248
+ function viteId(file) {
249
+ return path.resolve(file).split(path.sep).join("/");
250
+ }
251
+ /** `jestCompatSetup`, as a specifier or a path to the built file. */
252
+ const JEST_COMPAT_SETUP = /(?:^vitest-native\/jest-compat\/setup|[\\/]jest-compat[\\/]setup\.mjs)$/;
253
+ /** Each warning once per process, though every project and run loads the module. */
254
+ const warned = /* @__PURE__ */ new Set();
255
+ function warnOnce(message) {
256
+ if (warned.has(message)) return;
257
+ warned.add(message);
258
+ console.warn(message);
259
+ }
260
+ /**
261
+ * The generated setup module: one `jest.mock()` per manual mock, with a factory loading
262
+ * its file, which the transform then adapts like any other. A package reactNative()
263
+ * already stands in for is left to it, with a warning.
264
+ */
265
+ function rootMocksSource(module, coveredBy) {
266
+ const shown = (file) => path.relative(module.root, file).split(path.sep).join("/");
267
+ for (const duplicate of module.duplicates) warnOnce([
268
+ `[vitest-native] duplicate manual mock found: ${duplicate.name}`,
269
+ " The following files share their name; please delete one of them:",
270
+ ...duplicate.files.map((file) => ` * ${shown(file)}`),
271
+ ` jestMockTransform() applies the last one listed, as Jest applies the one it reads last.`
272
+ ].join("\n"));
273
+ const calls = [];
274
+ for (const mock of module.mocks) {
275
+ const covered = coveredBy(mock.spec);
276
+ if (covered) {
277
+ warnOnce(`[vitest-native] ${shown(mock.file)} is not applied to ${mock.spec}: ${covered} stands in for it. Delete the manual mock (\`vitest-native migrate\` lists these), or switch that off to use the mock.`);
278
+ continue;
279
+ }
280
+ calls.push(`jest.mock(${jsString(mock.spec)}, ${manualMockFactory(mock.file)});`);
281
+ }
282
+ return `import { vi } from "vitest";\nawait vi.hoisted(async () => {\n await import(${jsString(viteId(jestCompatSetupFile()))});\n});\n${calls.join("\n")}\nexport {};\n`;
283
+ }
284
+ /**
285
+ * The jest-compat setup file this plugin ships, by path: the file `jestCompatSetup`
286
+ * resolves to from the project, so importing it is the same module, evaluated once.
287
+ * Resolved here, inside the package, because the generated module's own directory may not
288
+ * resolve the package by name (a project outside its install, as this repository's
289
+ * fixtures are).
290
+ */
291
+ let setupFile;
292
+ function jestCompatSetupFile() {
293
+ setupFile ??= fileURLToPath(import.meta.resolve("vitest-native/jest-compat/setup"));
294
+ return setupFile;
295
+ }
296
+ /**
297
+ * The factory that loads a manual mock's file. Named, so jest-compat's registry knows it
298
+ * for a manual mock (MANUAL_MOCK_FACTORY in node-registry.mjs): while it runs, the module
299
+ * it mocks is the real one, as under Jest.
300
+ */
301
+ function manualMockFactory(file) {
302
+ return `function __vnManualMock() { return jest.requireActual(${jsString(file)}); }`;
303
+ }
304
+ const UNSAFE_IN_CODE = {
305
+ "<": "\\u003C",
306
+ ">": "\\u003E",
307
+ "\b": "\\b",
308
+ "\f": "\\f",
309
+ "\n": "\\n",
310
+ "\r": "\\r",
311
+ " ": "\\t",
312
+ "\0": "\\0",
313
+ "\u2028": "\\u2028",
314
+ "\u2029": "\\u2029"
315
+ };
316
+ /**
317
+ * `value` as a JavaScript string literal for generated code: JSON's escaping, plus the
318
+ * characters JSON leaves as they are that could end a script tag or a line in the code
319
+ * around it. Every string the generated code carries (a module name, a file path) goes
320
+ * through this, never through concatenation.
321
+ */
322
+ function jsString(value) {
323
+ return JSON.stringify(value).replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, (char) => UNSAFE_IN_CODE[char] ?? char);
324
+ }
325
+ function adapt(ctx, code, id, project, manualMockFor = () => null) {
326
+ let ast;
327
+ try {
328
+ ast = ctx.parse(code);
329
+ } catch {
330
+ return null;
331
+ }
332
+ const candidates = /* @__PURE__ */ new Map();
333
+ const requireIsGlobal = !BINDS_REQUIRE.test(code);
334
+ walk(ast, (node) => {
335
+ const factory = mockFactoryOf(node);
336
+ if (!factory || factory.generator) return;
337
+ const calls = ownLoadCalls(factory, literalSpec(node.arguments[0]), requireIsGlobal);
338
+ if (calls.length > 0) candidates.set(factory, calls);
339
+ });
340
+ if (candidates.size === 0) return rewrite(code, ast, /* @__PURE__ */ new Map(), manualMockFor);
341
+ const specs = new Set([...candidates.values()].flat().map((call) => call.spec));
342
+ return Promise.all([...specs].map(async (spec) => {
343
+ try {
344
+ return [spec, isViteOwnedSource(await ctx.resolve(spec, id), project)];
345
+ } catch {
346
+ return [spec, false];
347
+ }
348
+ })).then((resolved) => {
349
+ const owned = new Set(resolved.filter(([, yes]) => yes).map(([spec]) => spec));
350
+ const toAsync = /* @__PURE__ */ new Map();
351
+ for (const [factory, calls] of candidates) {
352
+ const moved = calls.filter((call) => owned.has(call.spec));
353
+ if (moved.length > 0) toAsync.set(factory, moved);
354
+ }
355
+ return rewrite(code, ast, toAsync, manualMockFor);
356
+ });
357
+ }
185
358
  /** The factory of a `jest.mock`/`jest.doMock` call with an inline function factory. */
186
359
  function mockFactoryOf(node) {
187
360
  if (node.type !== "CallExpression" || node.arguments.length < 2) return null;
@@ -196,21 +369,22 @@ function mockFactoryOf(node) {
196
369
  * The transform itself. `toAsync` maps a factory to the `jest.requireActual` calls that
197
370
  * load through Vite instead (see "`jest.requireActual` of project source" above).
198
371
  */
199
- function rewrite(code, ast, toAsync) {
372
+ function rewrite(code, ast, toAsync, manualMockFor = () => null) {
200
373
  const s = new MagicString(code);
201
374
  let changed = false;
202
375
  const topLevel = /* @__PURE__ */ new Map();
203
376
  for (const statement of ast.body) if (statement.type === "ExpressionStatement") topLevel.set(statement.expression, statement);
204
377
  let usesSetup = false;
205
378
  const replaced = [];
206
- /** The factory's source, async, with its own project `requireActual`s via Vite. */
379
+ /** The factory's source, async, with its own project loads via Vite. */
207
380
  const asyncFactory = (factory, calls) => {
208
381
  let text = "";
209
382
  let at = factory.start;
210
- for (const call of [...calls].sort((a, b) => a.start - b.start)) {
383
+ for (const { node: call, kind } of [...calls].sort((a, b) => a.node.start - b.node.start)) {
211
384
  const arg = call.arguments[0];
385
+ const spec = code.slice(arg.start, arg.end);
212
386
  text += code.slice(at, call.start);
213
- text += `(${SETUP}("__vnActualExports")(await vi.importActual(${code.slice(arg.start, arg.end)})))`;
387
+ text += kind === "require" ? `(await ${SETUP}("__vnFactoryRequire")(import.meta.url, ${spec}, () => import(${spec})))` : `(${SETUP}("__vnActualExports")(await vi.importActual(${spec})))`;
214
388
  at = call.end;
215
389
  }
216
390
  text += code.slice(at, factory.end);
@@ -227,8 +401,20 @@ function rewrite(code, ast, toAsync) {
227
401
  if (!prop || prop.type !== "Identifier" || !HOISTABLE.has(prop.name)) return;
228
402
  s.overwrite(obj.start, obj.end, "vi");
229
403
  changed = true;
404
+ if ((prop.name === "mock" || prop.name === "unmock") && !topLevel.has(node)) s.overwrite(prop.start, prop.end, prop.name === "mock" ? "doMock" : "doUnmock");
230
405
  const specNode = node.arguments[0];
231
406
  const spec = specNode && (specNode.type === "Literal" && typeof specNode.value === "string" || specNode.type === "TemplateLiteral" && specNode.expressions.length === 0 || specNode.type === "Identifier") ? code.slice(specNode.start, specNode.end) : null;
407
+ const literal = specNode && specNode.type === "Literal" && typeof specNode.value === "string" ? specNode.value : null;
408
+ const manualMock = prop.name === "mock" && node.arguments.length === 1 && literal !== null ? manualMockFor(literal) : null;
409
+ const mockStatement = topLevel.get(node);
410
+ if (manualMock !== null && mockStatement) {
411
+ usesSetup = true;
412
+ const name = jsString(literal);
413
+ const register = `globalThis.__vnJestMock?.(import.meta.url, ${name}, ${manualMockFactory(manualMock)}, ${`async () => (${SETUP}("__vnActualExports")(await vi.importActual(${jsString(viteId(manualMock))})))`})`;
414
+ s.prependLeft(mockStatement.start, `vi.hoisted(() => ${register});\n`);
415
+ s.appendLeft(specNode.end, `, () => ${SETUP}("__vnJestMocked")(import.meta.url, ${name})`);
416
+ return;
417
+ }
232
418
  if (WITH_FACTORY.has(prop.name) && node.arguments.length >= 2) {
233
419
  const factory = node.arguments[1];
234
420
  if (factory.type === "ArrowFunctionExpression" || factory.type === "FunctionExpression") {
@@ -258,11 +444,10 @@ function rewrite(code, ast, toAsync) {
258
444
  s.appendRight(specNode.end, ")");
259
445
  }
260
446
  });
261
- if (!changed) return null;
262
- if (usesSetup) s.prepend(SETUP_ACCESSOR);
263
447
  return {
264
- code: s.toString(),
265
- map: s.generateMap({ hires: true })
448
+ s,
449
+ changed,
450
+ usesSetup
266
451
  };
267
452
  }
268
453
  // src/jest-compat/index.ts
@@ -1,4 +1,3 @@
1
- /// <reference types="vitest" />
2
1
  /**
3
2
  * Reanimated-compatible matchers: `toHaveAnimatedStyle` and `toHaveAnimatedProps`.
4
3
  *
@@ -1,4 +1,3 @@
1
- /// <reference types="vitest" />
2
1
  /**
3
2
  * Reanimated-compatible matchers: `toHaveAnimatedStyle` and `toHaveAnimatedProps`.
4
3
  *
@@ -26,6 +26,7 @@ import fs from "node:fs";
26
26
  import { createRequire } from "node:module";
27
27
  import path from "node:path";
28
28
  import { VitestNativeError } from "../errors.mjs";
29
+ import { relativeToRoot } from "./root-spelling.mjs";
29
30
 
30
31
  // metro-config/src/defaults/defaults.js `assetExts` (0.87): the extensions Metro
31
32
  // resolves as assets when a project's Metro config adds none. One list for the plugin
@@ -299,7 +300,8 @@ export function metroAssetDescriptor(file, { projectRoot, platform }) {
299
300
  // project root, under publicPath; a path escaping the root keeps its `..`.
300
301
  const expo = expoBundlesAssets(projectRoot);
301
302
  const publicPath = expo ? EXPO_PUBLIC_PATH : PUBLIC_PATH;
302
- const localDir = path.dirname(path.relative(projectRoot, file));
303
+ // In whichever spelling of the root the file is under (root-spelling.mjs).
304
+ const localDir = path.dirname(relativeToRoot(projectRoot, file));
303
305
  let urlPath = (
304
306
  localDir.startsWith("..")
305
307
  ? `${publicPath.replace(/\/$/, "")}/${localDir}`
@@ -0,0 +1,13 @@
1
+ export declare function projectBabelCaller(options: {
2
+ hasExpo: boolean;
3
+ platform: string;
4
+ esm: boolean;
5
+ }): {
6
+ name: string;
7
+ bundler?: string;
8
+ platform?: string;
9
+ supportsDynamicImport: boolean;
10
+ supportsExportNamespaceFrom: boolean;
11
+ supportsStaticESM: boolean;
12
+ supportsTopLevelAwait: boolean;
13
+ };
@@ -0,0 +1,24 @@
1
+ // The caller Babel sees for project source, wherever the engine compiles it: Node's
2
+ // require (transform.mjs, CommonJS out) and Vite's load (project-babel.ts, ES modules
3
+ // out). A config's `api.caller` branches take the same name and platform on both sides,
4
+ // as babel-jest's and Metro's do; only the module-format flags differ, because each side
5
+ // needs its own output.
6
+
7
+ /**
8
+ * babel-jest's caller (babel-jest 29.7, build/index.js:196-237), or jest-expo's Metro
9
+ * caller with the platform when the project has Expo (jest-expo 57,
10
+ * config/getPlatformPreset.js:48-66), which babel-preset-expo reads to inline
11
+ * Platform.OS and process.env.EXPO_OS.
12
+ * `esm`: ES modules out (Vite), else CommonJS (Node, Jest's defaults without
13
+ * --experimental-vm-modules, jest-runtime 29.7 build/index.js:173-179).
14
+ */
15
+ export function projectBabelCaller({ hasExpo, platform, esm }) {
16
+ const flags = {
17
+ supportsDynamicImport: esm,
18
+ supportsExportNamespaceFrom: esm,
19
+ supportsStaticESM: esm,
20
+ supportsTopLevelAwait: esm,
21
+ };
22
+ if (hasExpo) return { name: "metro", bundler: "metro", platform, ...flags };
23
+ return { name: "babel-jest", ...flags };
24
+ }
@@ -22,8 +22,9 @@ function babelFor(root) {
22
22
  function loadPartial(request) {
23
23
  return babelFor(request.root).loadPartialConfig({
24
24
  filename: request.file,
25
- cwd: request.root,
26
- root: request.root,
25
+ // Spelled as the file is (root-spelling.mjs), so Babel finds the .babelrc files above it.
26
+ cwd: request.babelRoot ?? request.root,
27
+ root: request.babelRoot ?? request.root,
27
28
  caller: request.caller,
28
29
  });
29
30
  }
@@ -117,9 +118,15 @@ function importMetaUnsupported(file, root, name, at) {
117
118
  const shown = shownPath.split(path.sep).join("/");
118
119
  const where = at ? `${shown}:${at.line}:${at.column + 1}` : shown;
119
120
  const pkg = owningPackage(file, root);
121
+ // Vitest leaves a package Node can run as published (an ES module) to Node, so
122
+ // excluding it from compiling is not enough for Vite to load it: it must be inlined too.
123
+ const inline = runsAsModule(file)
124
+ ? ` and to \`test: { server: { deps: { inline: [...] } } }\`, since Node otherwise ` +
125
+ `runs it as the ES module it is published as`
126
+ : "";
120
127
  const fix = pkg
121
128
  ? `To fix it, let Vite load '${pkg}': add it to \`transform: { exclude: [...] }\` in ` +
122
- `reactNative()'s options. Or do not use ${what} in code Node loads.`
129
+ `reactNative()'s options${inline}. Or do not use ${what} in code Node loads.`
123
130
  : `To fix it, import the file from the test so Vite loads it, rather than requiring it ` +
124
131
  `(require(), jest.requireActual). Or do not use ${what} in code Node loads.`;
125
132
  return new VitestNativeError(
@@ -143,6 +150,22 @@ function owningPackage(file, root) {
143
150
  return null;
144
151
  }
145
152
 
153
+ /**
154
+ * Whether Node runs `file` as an ES module as published: `.mjs`, or `.js` under the
155
+ * nearest package.json's `"type": "module"`. Vitest's own check (isValidNodeImport)
156
+ * externalizes such a file; one Node cannot run (TypeScript, or ESM syntax in a
157
+ * CommonJS package) it inlines.
158
+ */
159
+ function runsAsModule(file) {
160
+ if (file.endsWith(".mjs")) return true;
161
+ if (!file.endsWith(".js")) return false;
162
+ for (let dir = path.dirname(file); path.dirname(dir) !== dir; dir = path.dirname(dir)) {
163
+ const manifest = readManifest(dir);
164
+ if (manifest) return manifest.type === "module";
165
+ }
166
+ return false;
167
+ }
168
+
146
169
  /** `dir`'s package.json, or null when it has none it can read. */
147
170
  function readManifest(dir) {
148
171
  try {
@@ -154,6 +177,7 @@ function readManifest(dir) {
154
177
 
155
178
  function realPath(dir) {
156
179
  try {
180
+ // The OS's spelling (realpathSync.native), on both sides of owningPackage's comparison.
157
181
  return fs.realpathSync.native(dir);
158
182
  } catch {
159
183
  return path.resolve(dir);
@@ -68,7 +68,8 @@ function deviceConstants(platform, reactNativeVersion) {
68
68
  };
69
69
  }
70
70
 
71
- // A reusable mock-native-component factory, inlined into each source string that needs it.
71
+ // The mock-native-component factory, inlined into NativeComponentRegistry's source, which
72
+ // memoizes one class per view name for the other routes to host components.
72
73
  //
73
74
  // For RCTScrollView we drop the scroll-responder negotiation props that real
74
75
  // ScrollView attaches to its host (onStartShouldSetResponder &co). On a device
@@ -97,6 +98,14 @@ const MOCK_NATIVE_COMPONENT = `
97
98
  ]);
98
99
  const mockNativeComponent = (viewName) => {
99
100
  const hostName = __TEXT_INPUT_VIEWS.has(viewName) ? "TextInput" : viewName;
101
+ // The native methods a ref has, on a plain object the class delegates to: a spy that
102
+ // replaces one there reaches every ref of this view. jest-compat gives it to View,
103
+ // Text and ScrollView as their prototype, as React Native's Jest preset has one. It
104
+ // is not the class's own prototype, which would make React construct those function
105
+ // components as classes.
106
+ const nativeMethods = {
107
+ blur() {}, focus() {}, measure() {}, measureInWindow() {}, measureLayout() {}, setNativeProps() {},
108
+ };
100
109
  const C = class extends React.Component {
101
110
  constructor(p) { super(p); this._nativeTag = __tag++; }
102
111
  render() {
@@ -107,9 +116,15 @@ const MOCK_NATIVE_COMPONENT = `
107
116
  }
108
117
  return React.createElement(hostName, props, props.children);
109
118
  }
110
- blur() {} focus() {} measure() {} measureInWindow() {} measureLayout() {} setNativeProps() {}
119
+ blur(...a) { return nativeMethods.blur.apply(this, a); }
120
+ focus(...a) { return nativeMethods.focus.apply(this, a); }
121
+ measure(...a) { return nativeMethods.measure.apply(this, a); }
122
+ measureInWindow(...a) { return nativeMethods.measureInWindow.apply(this, a); }
123
+ measureLayout(...a) { return nativeMethods.measureLayout.apply(this, a); }
124
+ setNativeProps(...a) { return nativeMethods.setNativeProps.apply(this, a); }
111
125
  };
112
126
  C.displayName = viewName === "RCTView" ? "View" : hostName;
127
+ C.nativeMethods = nativeMethods;
113
128
  return C;
114
129
  };
115
130
  `;
@@ -296,19 +311,41 @@ export const BOUNDARY_SOURCES = {
296
311
  has: (_t, n) => typeof n === "string" && isKnownModule(n),
297
312
  }) };
298
313
  `,
314
+ // The one place the boundary's host component classes are made, one per native view
315
+ // name: requireNativeComponent, ViewNativeComponent and createReactNativeComponentClass
316
+ // all ask it. Every RCTView host is then an instance of the same class, whichever path
317
+ // rendered it, so a host ref's methods live on one prototype (jest-compat exposes it as
318
+ // View.prototype, as React Native's Jest preset has one; jest-compat/setup.mjs).
299
319
  "Libraries/NativeComponent/NativeComponentRegistry.js": `
300
320
  ${MOCK_NATIVE_COMPONENT}
301
- exports.get = (n) => mockNativeComponent(n);
302
- exports.getWithFallback_DEPRECATED = (n) => mockNativeComponent(n);
321
+ const __classes = new Map();
322
+ const get = (n) => {
323
+ let C = __classes.get(n);
324
+ if (!C) __classes.set(n, (C = mockNativeComponent(n)));
325
+ return C;
326
+ };
327
+ exports.get = get;
328
+ exports.getWithFallback_DEPRECATED = get;
303
329
  exports.setRuntimeConfigProvider = () => {};
304
330
  `,
305
331
  "Libraries/ReactNative/requireNativeComponent.js": `
306
- ${MOCK_NATIVE_COMPONENT}
307
- module.exports = { __esModule: true, default: (n) => mockNativeComponent(n) };
332
+ const { get } = require("react-native/Libraries/NativeComponent/NativeComponentRegistry");
333
+ module.exports = { __esModule: true, default: get };
334
+ `,
335
+ // The last route to a host component that bypassed the boundary: Text's RCTText,
336
+ // RCTVirtualText and RCTSelectableText (TextNativeComponent.js). The real shim only
337
+ // registers a view config and returns the name, so React rendered a bare string host:
338
+ // React 19 passed it \`ref\` as a prop, which test-renderer's toJSON printed, and a Text
339
+ // ref was a renderer instance without measure() and the other native methods a View
340
+ // ref has. Through the boundary class, as View's host is, the ref is an instance with
341
+ // those methods, and \`ref\` is not among the host's props.
342
+ "Libraries/Renderer/shims/createReactNativeComponentClass.js": `
343
+ const { get } = require("react-native/Libraries/NativeComponent/NativeComponentRegistry");
344
+ module.exports = { __esModule: true, default: get };
308
345
  `,
309
346
  "Libraries/Components/View/ViewNativeComponent.js": `
310
- ${MOCK_NATIVE_COMPONENT}
311
- module.exports = { __esModule: true, default: mockNativeComponent("RCTView"), __INTERNAL_VIEW_CONFIG: {}, Commands: {} };
347
+ const { get } = require("react-native/Libraries/NativeComponent/NativeComponentRegistry");
348
+ module.exports = { __esModule: true, default: get("RCTView"), __INTERNAL_VIEW_CONFIG: {}, Commands: {} };
312
349
  `,
313
350
  // TextInput: mirror react-native/jest/setup.js, which replaces the real TextInput
314
351
  // with a passthrough host component (jest/mocks/TextInput, via mockComponent).