vitest-native 0.15.0 → 0.16.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/cli.mjs +177 -31
  2. package/dist/context.d.mts +6 -0
  3. package/dist/context.mjs +5 -0
  4. package/dist/errors.d.mts +5 -0
  5. package/dist/hang-watch.d.mts +2 -0
  6. package/dist/hang-watch.mjs +60 -3
  7. package/dist/{host-TAGjG56H.mjs → host-X6VHF-a4.mjs} +456 -15
  8. package/dist/{index-BpZ0E2eJ.d.mts → index-X3wuvaqa.d.mts} +25 -13
  9. package/dist/index.d.mts +3 -3
  10. package/dist/index.mjs +220 -117
  11. package/dist/jest-compat/jest-object.mjs +62 -17
  12. package/dist/jest-compat/node-registry.mjs +496 -126
  13. package/dist/jest-compat/setup.mjs +32 -4
  14. package/dist/jest-compat.cjs +277 -33
  15. package/dist/jest-compat.d.cts +1 -1
  16. package/dist/jest-compat.d.mts +1 -1
  17. package/dist/jest-compat.mjs +257 -33
  18. package/dist/native/assets.mjs +41 -10
  19. package/dist/native/babel-worker.mjs +4 -2
  20. package/dist/native/boundary.mjs +52 -14
  21. package/dist/native/bounded-process.mjs +110 -27
  22. package/dist/native/explain.mjs +101 -5
  23. package/dist/native/expo-module-mocks.mjs +3 -0
  24. package/dist/native/gesture-handler-buttons.mjs +148 -0
  25. package/dist/native/hooks.mjs +8 -2
  26. package/dist/native/hot-diagnostic.mjs +7 -0
  27. package/dist/native/library-jest.mjs +16 -8
  28. package/dist/native/loader.mjs +159 -2
  29. package/dist/native/metro-profile-compiler.mjs +2 -1
  30. package/dist/native/metro-profile.mjs +2 -0
  31. package/dist/native/ownership-ledger.d.mts +2 -0
  32. package/dist/native/ownership-ledger.mjs +3 -2
  33. package/dist/native/react-dedupe.d.mts +7 -0
  34. package/dist/native/react-dedupe.mjs +191 -0
  35. package/dist/native/registry-compiler.mjs +3 -2
  36. package/dist/native/registry-process.mjs +90 -12
  37. package/dist/native/registry.mjs +9 -4
  38. package/dist/native/reset.mjs +51 -26
  39. package/dist/native/resolve.mjs +5 -1
  40. package/dist/native/setup.mjs +15 -7
  41. package/dist/native/state-manifest.mjs +2 -3
  42. package/dist/native/transform.mjs +125 -3
  43. package/dist/native/worker.mjs +3 -12
  44. package/dist/node-dispatch.mjs +2 -0
  45. package/dist/preset-react.d.mts +11 -0
  46. package/dist/preset-react.mjs +121 -0
  47. package/dist/{presets-DLH7uRGA.mjs → presets-Dw0Sz9O6.mjs} +1352 -567
  48. package/dist/presets.d.mts +1 -1
  49. package/dist/presets.mjs +1 -1
  50. package/dist/setup-files-C6-77IIs.mjs +22 -0
  51. package/dist/setup.mjs +15 -13
  52. package/package.json +15 -5
  53. package/dist/memory-Couw0Esx.mjs +0 -151
  54. package/dist/native/compile-cache.mjs +0 -57
@@ -14,7 +14,12 @@ import fs from "node:fs";
14
14
  import path from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { expandAlias } from "./aliases.mjs";
17
- import { expandResolutionAlias } from "../native/shared-resolver.mjs";
17
+ import {
18
+ conditionsIn,
19
+ expandResolutionAlias,
20
+ exportTarget,
21
+ nodeOptionsList,
22
+ } from "../native/shared-resolver.mjs";
18
23
  import {
19
24
  isWholePackageRequest,
20
25
  resolvePackageMainField,
@@ -23,7 +28,7 @@ import {
23
28
  resolveRelativePlatformFile,
24
29
  } from "../native/resolve.mjs";
25
30
  import { resetEvaluatedModules, restoreEvaluatedModules } from "../native/module-reset.mjs";
26
- import { VitestNativeError } from "../errors.mjs";
31
+ import { VitestNativeError, VitestNativeTypeError, isVitestNativeError } from "../errors.mjs";
27
32
  import { activeRegistry, projectContext } from "../context.mjs";
28
33
  import { nodeDispatch } from "../node-dispatch.mjs";
29
34
  import { isRuntimeResidentFile } from "../native/ownership.mjs";
@@ -179,6 +184,17 @@ function createState() {
179
184
  entries: new WatchedMap(changed),
180
185
  /** Specifiers no resolver could place (Jest's virtual mocks) -> entry. */
181
186
  unresolved: new WatchedMap(changed),
187
+ /**
188
+ * Root mocks (`__mocks__` manual mocks of a package), by the spec they mock: Jest
189
+ * matches one by request name, in every installed copy (copyEntryOf).
190
+ */
191
+ byName: new WatchedMap(changed),
192
+ /**
193
+ * Files a `jest.unmock` took a root mock off: those of the copy the test file resolves
194
+ * the spec to. Other copies keep the root mock, as under Jest, which records the unmock
195
+ * for that module id only (`_explicitShouldMock`).
196
+ */
197
+ unmocked: new Set(),
182
198
  /** `parentFile\0request` -> resolved file or null. Valid for the worker's life. */
183
199
  resolutions: new Map(),
184
200
  /** What `requireActual` is loading: its next load skips the mock. */
@@ -267,6 +283,142 @@ function createState() {
267
283
  return state.resolve(spec, file ? parentModuleFor(file) : rootParent);
268
284
  };
269
285
 
286
+ /**
287
+ * The file an `import` of the package subpath `spec` from `from` resolves to, when
288
+ * `require` cannot resolve it: an ES-module package whose `exports` gives the subpath
289
+ * an `import` condition only (`multiformats/cid`). Without it such a jest.mock was
290
+ * registered by its specifier only, which a `require` matches, but Node's ESM loader
291
+ * looks a registration up by the file it resolved, so the import was matched against
292
+ * Vitest's copy of the mock, whose factory is async (#896). Node's ESM resolution of a
293
+ * package's `exports`, with Node's conditions: an answer it would not give leaves the
294
+ * import unmatched, which fails by name (MOCK_NOT_SEEN_BY_NODE), as before.
295
+ */
296
+ function importOnlyFile(spec, from) {
297
+ if (typeof spec !== "string" || !isBare(spec) || Module.isBuiltin(spec)) return null;
298
+ const name = packageNameOf(spec);
299
+ const anchor =
300
+ typeof from === "string" && from.startsWith("file:") ? fileURLToPath(from) : from;
301
+ for (let dir = path.dirname(anchor || rootFile); ; dir = path.dirname(dir)) {
302
+ const pkgDir = path.join(dir, "node_modules", name);
303
+ let manifest;
304
+ try {
305
+ manifest = JSON.parse(fs.readFileSync(path.join(pkgDir, "package.json"), "utf8"));
306
+ } catch {
307
+ manifest = undefined; // Not installed here, or unreadable: Node looks further up.
308
+ }
309
+ if (manifest !== undefined) return exportFileIn(pkgDir, manifest, subpathOf(spec));
310
+ if (path.dirname(dir) === dir) return null;
311
+ }
312
+ }
313
+
314
+ /** The `exports` key a bare `spec` names in its package: `.` or `./sub`. */
315
+ const subpathOf = (spec) => `.${spec.slice(packageNameOf(spec).length)}`;
316
+
317
+ /** The file an import of `subpath` loads from the package at `pkgDir`, or null. */
318
+ function exportFileIn(pkgDir, manifest, subpath) {
319
+ const target = exportTarget(manifest.exports, subpath, IMPORT_CONDITIONS);
320
+ if (typeof target !== "string" || !validTarget(target)) return null;
321
+ const file = path.join(pkgDir, target);
322
+ return fs.existsSync(file) ? canonical(file) : null;
323
+ }
324
+
325
+ /**
326
+ * A root mock (a `__mocks__` manual mock) of a package, for the files any installed
327
+ * copy of the package gives its subpath (#898). Jest matches a root mock by name
328
+ * (jest-runtime's `requireModule` takes `getMockModule(from, name)` for any `from`), so
329
+ * every copy is mocked, through `import` and `require` alike: one in node_modules, and
330
+ * one a workspace or `file:` dependency links to, at its real path outside it (#899).
331
+ * An explicit jest.mock factory is keyed by the files of the copy it resolves to, under
332
+ * Jest too, so it is not matched here. Undefined when no such mock applies to `file`.
333
+ */
334
+ const copyFiles = new Map();
335
+ function copyEntryOf(file) {
336
+ const index = reachIndex();
337
+ if (index.copies.size === 0) return undefined;
338
+ const copy = copyOf(file);
339
+ const candidates = copy === null ? undefined : index.copies.get(copy.name);
340
+ if (candidates === undefined) return undefined;
341
+ for (const entry of candidates) {
342
+ if (filesOfCopy(copy.dir, entry.spec).includes(file)) return entry;
343
+ }
344
+ return undefined;
345
+ }
346
+
347
+ /**
348
+ * The files the copy of a package at `pkgDir` gives the bare `spec`: Node's `import`
349
+ * target, from its `exports`, and Node's `require` answer for that copy. Jest gives a
350
+ * module one id whichever of them a request reaches, so a mock or an unmock of the spec
351
+ * covers them all. Cached: installed files do not change within a worker.
352
+ */
353
+ function filesOfCopy(pkgDir, spec) {
354
+ const key = `${pkgDir}\0${spec}`;
355
+ let files = copyFiles.get(key);
356
+ if (files !== undefined) return files;
357
+ files = [];
358
+ let manifest;
359
+ try {
360
+ manifest = JSON.parse(fs.readFileSync(path.join(pkgDir, "package.json"), "utf8"));
361
+ } catch {
362
+ manifest = null; // No readable manifest: no `exports` for an import to follow.
363
+ }
364
+ const imported = manifest === null ? null : exportFileIn(pkgDir, manifest, subpathOf(spec));
365
+ if (imported !== null) files.push(imported);
366
+ const required = requiredFileOf(pkgDir, manifest, spec);
367
+ if (required !== null && required !== imported && copyOf(required)?.dir === pkgDir) {
368
+ files.push(required);
369
+ }
370
+ copyFiles.set(key, files);
371
+ return files;
372
+ }
373
+
374
+ /**
375
+ * Node's `require` answer for `spec` in the copy at `pkgDir`. An installed copy is its
376
+ * own from beside it (its `node_modules` directory holds it under its name, an npm
377
+ * alias's included). A linked copy is outside any: its own `exports` by
378
+ * self-reference, as Node resolves a package's name from inside it, or else the file
379
+ * its subpath names.
380
+ */
381
+ function requiredFileOf(pkgDir, manifest, spec) {
382
+ const at = pkgDir.lastIndexOf("/node_modules/");
383
+ if (at !== -1 && installedPackageDirOf(path.join(pkgDir, "package.json")) === pkgDir) {
384
+ return nodeResolution(spec, parentModuleFor(path.join(pkgDir.slice(0, at), "package.json")));
385
+ }
386
+ if (manifest?.exports !== undefined) {
387
+ return nodeResolution(spec, parentModuleFor(path.join(pkgDir, "package.json")));
388
+ }
389
+ return nodeResolution(path.join(pkgDir, spec.slice(packageNameOf(spec).length)), rootParent);
390
+ }
391
+
392
+ /**
393
+ * The files a `jest.mock` or `jest.unmock` of `spec` covers, given the file it resolves
394
+ * to: for a package, every file its copy gives the spec (filesOfCopy); else that file.
395
+ */
396
+ function filesOfSpec(spec, filename) {
397
+ const copy = isBare(spec) ? copyOf(filename) : null;
398
+ if (copy === null || copy.name !== packageNameOf(spec)) return [filename];
399
+ const files = filesOfCopy(copy.dir, spec);
400
+ return files.includes(filename) ? files : [filename, ...files];
401
+ }
402
+
403
+ /**
404
+ * The jest.mock a request for `file` (a real path) gets, `request` as written: the one
405
+ * registered for that file, or a root mock of it in another copy. A relative request of
406
+ * a file a root mock covers gets BYPASSED, the real module. Jest matches a root mock by
407
+ * name, and its module id for a request includes the root mock it names (jest-resolve
408
+ * `getModuleID`), so a package's own relative import of the file is the real module,
409
+ * past an explicit jest.mock of the spec too (#899). A request by name, or by the
410
+ * absolute path the engine's own loads use (its ESM mock facade, React Native's
411
+ * precompiled registry), is matched by file.
412
+ */
413
+ state.entryOf = (file, request) => {
414
+ const relative = typeof request === "string" && request.startsWith(".");
415
+ const registered = state.entries.get(file);
416
+ if (registered !== undefined && !relative) return registered;
417
+ const byName = copyEntryOf(file);
418
+ if (relative && byName !== undefined) return BYPASSED;
419
+ return registered ?? (state.unmocked.has(file) ? undefined : byName);
420
+ };
421
+
270
422
  // The memoized mock: `requireMock` caches the factory's result in `_mockRegistry`.
271
423
  //
272
424
  // A factory jestMockTransform made async (its `jest.requireActual` of project source
@@ -354,7 +506,7 @@ function createState() {
354
506
  state.bypass = null;
355
507
  return BYPASSED;
356
508
  }
357
- return filename !== null ? state.entries.get(filename) : state.unresolved.get(request);
509
+ return filename !== null ? state.entryOf(filename, request) : state.unresolved.get(request);
358
510
  };
359
511
 
360
512
  // `asyncFactory` is jestMockTransform's async variant of `factory`, when it made one.
@@ -362,15 +514,27 @@ function createState() {
362
514
  // whose lifetime the native setup decides at each file boundary; `owner` is what it
363
515
  // keeps it by.
364
516
  state.register = (from, spec, factory, asyncFactory, { library = false, owner = null } = {}) => {
365
- const filename = state.resolveFrom(spec, from);
517
+ const required = state.resolveFrom(spec, from);
518
+ const filename = required ?? importOnlyFile(spec, from);
519
+ const files = filename === null ? [] : filesOfSpec(spec, filename);
520
+ // A manual mock (a __mocks__ file, jest-compat/root-mocks.ts): while it executes, a
521
+ // request for the module it mocks is the real module, as jest-runtime's
522
+ // `_isCurrentlyExecutingManualMock` has it, not a cycle.
523
+ const manual = factory?.name === MANUAL_MOCK_FACTORY;
366
524
  const entry = {
367
525
  spec,
526
+ // The file that registered it and the file it mocks, for an error that names it.
527
+ from,
528
+ filename,
368
529
  factory,
369
530
  asyncFactory,
370
- // A manual mock (a __mocks__ file, jest-compat/root-mocks.ts): while it executes, a
371
- // request for the module it mocks is the real module, as jest-runtime's
372
- // `_isCurrentlyExecutingManualMock` has it, not a cycle.
373
- manual: factory?.name === MANUAL_MOCK_FACTORY,
531
+ manual,
532
+ // A root mock of a package reaches its subpath in every copy of the package.
533
+ everyCopy:
534
+ manual &&
535
+ filename !== null &&
536
+ isBare(spec) &&
537
+ copyOf(filename)?.name === packageNameOf(spec),
374
538
  has: false,
375
539
  value: undefined,
376
540
  pending: null,
@@ -378,15 +542,30 @@ function createState() {
378
542
  library,
379
543
  owner,
380
544
  };
381
- if (filename !== null) {
382
- state.entries.set(filename, entry);
383
- state.decided.add(canonical(filename));
384
- } else state.unresolved.set(spec, entry);
545
+ // Every file of the copy the test file resolves: an `import` of a dual subpath reaches
546
+ // another file than a `require` (#899).
547
+ for (const file of files) {
548
+ state.entries.set(file, entry);
549
+ state.decided.add(canonical(file));
550
+ state.unmocked.delete(file);
551
+ }
552
+ // A root mock stays matched by name in other copies when an explicit jest.mock
553
+ // replaces it for the test file's own, as under Jest (#899).
554
+ if (entry.everyCopy) state.byName.set(spec, entry);
555
+ // A spec only `import` resolves is also kept by name: a `require` of it, which
556
+ // Node cannot resolve, looks it up so (jest.requireMock, a factory's require).
557
+ if (required === null) state.unresolved.set(spec, entry);
385
558
  // The hoisted `vi.mock` factory looks its entry up by where it was written.
386
559
  state.byCall.set(`${from}\0${spec}`, entry);
387
560
  return entry;
388
561
  };
389
562
  state.byCall = new Map();
563
+ /**
564
+ * The entries served to each file's Node `require`s, by that file: a module that fails
565
+ * while it loads because one of them lacks an export it uses is reported by the mock's
566
+ * name (missingExportError).
567
+ */
568
+ state.served = new Map();
390
569
  /**
391
570
  * The files a jest.* call registered or unregistered in this test file. Jest-compat
392
571
  * applies each to Node's require at once, and also queues it with Vitest for the
@@ -396,10 +575,12 @@ function createState() {
396
575
  state.decided = new Set();
397
576
 
398
577
  state.unregister = (from, spec) => {
399
- const filename = state.resolveFrom(spec, from);
400
- if (filename !== null) {
401
- state.entries.delete(filename);
402
- state.decided.add(canonical(filename));
578
+ const filename = state.resolveFrom(spec, from) ?? importOnlyFile(spec, from);
579
+ for (const file of filename === null ? [] : filesOfSpec(spec, filename)) {
580
+ state.entries.delete(file);
581
+ state.decided.add(canonical(file));
582
+ // Off this copy only: another copy keeps a root mock of the spec (#899).
583
+ state.unmocked.add(file);
403
584
  }
404
585
  state.unresolved.delete(spec);
405
586
  };
@@ -469,7 +650,9 @@ function createState() {
469
650
  return dropped;
470
651
  };
471
652
 
472
- const allEntries = () => [...state.entries.values(), ...state.unresolved.values()];
653
+ const allEntries = (state.allEntries = () => [
654
+ ...new Set([...state.entries.values(), ...state.unresolved.values(), ...state.byName.values()]),
655
+ ]);
473
656
  const forget = (entry) => {
474
657
  entry.has = false;
475
658
  entry.value = undefined;
@@ -492,6 +675,7 @@ function createState() {
492
675
  state.isolation = null;
493
676
  state.dropProjectModules();
494
677
  allEntries().forEach(forget);
678
+ state.served.clear();
495
679
  return Boolean(modules);
496
680
  };
497
681
 
@@ -546,14 +730,18 @@ function createState() {
546
730
  };
547
731
  keep(state.entries);
548
732
  keep(state.unresolved);
733
+ keep(state.byName);
549
734
  keep(state.byCall);
735
+ state.unmocked.clear();
736
+ state.served.clear();
550
737
  // Decisions are derived from the registrations: recomputed after any clear.
551
738
  state.decided.clear();
552
739
  state.bypass = null;
553
740
  state.isolation = null;
554
741
  };
555
742
 
556
- state.isEmpty = () => state.entries.size === 0 && state.unresolved.size === 0;
743
+ state.isEmpty = () =>
744
+ state.entries.size === 0 && state.unresolved.size === 0 && state.byName.size === 0;
557
745
 
558
746
  /**
559
747
  * What the registered mocks can be reached by, rebuilt after a registration changes:
@@ -566,6 +754,13 @@ function createState() {
566
754
  if (reach !== null) return reach;
567
755
  const names = new Set();
568
756
  const dirs = new Set();
757
+ const copies = new Map();
758
+ for (const entry of state.byName.values()) {
759
+ const name = packageNameOf(entry.spec);
760
+ if (!copies.has(name)) copies.set(name, []);
761
+ copies.get(name).push(entry);
762
+ names.add(name);
763
+ }
569
764
  let wide = false;
570
765
  for (const [file, entry] of state.entries) {
571
766
  const dir = installedPackageDirOf(file);
@@ -584,7 +779,7 @@ function createState() {
584
779
  if (isBare(spec)) names.add(packageNameOf(spec));
585
780
  else wide = true;
586
781
  }
587
- reach = { names, dirs, wide, aliased: new Map() };
782
+ reach = { names, dirs, wide, aliased: new Map(), copies };
588
783
  return reach;
589
784
  }
590
785
 
@@ -616,7 +811,9 @@ function createState() {
616
811
  }
617
812
  if (from === null && !path.isAbsolute(request)) return true;
618
813
  const target = from === null ? request : path.resolve(path.dirname(from), request);
619
- return index.dirs.has(installedPackageDirOf(target));
814
+ if (index.dirs.has(installedPackageDirOf(target))) return true;
815
+ // A root mock reaches every copy of its package (copyEntryOf), wherever installed.
816
+ return index.copies.size > 0 && index.copies.has(copyOf(target)?.name);
620
817
  };
621
818
 
622
819
  return state;
@@ -711,6 +908,19 @@ function bridgedInstanceOf(filename, parent) {
711
908
  return Object.prototype.toString.call(value) === "[object Module]" ? requireFacade(value) : value;
712
909
  }
713
910
 
911
+ /**
912
+ * The conditions Node's ESM loader resolves an import with in this process: its defaults
913
+ * (`node-addons` unless addons are off) and the `--conditions` it was given.
914
+ */
915
+ const NODE_OPTIONS = [...process.execArgv, ...nodeOptionsList(process.env.NODE_OPTIONS)];
916
+ const IMPORT_CONDITIONS = [
917
+ "node",
918
+ "import",
919
+ "module-sync",
920
+ ...(NODE_OPTIONS.includes("--no-addons") ? [] : ["node-addons"]),
921
+ ...conditionsIn(NODE_OPTIONS),
922
+ ];
923
+
714
924
  /**
715
925
  * A bare specifier (a package name). Aliases need no check here: the require hooks
716
926
  * apply them only after Node fails, so Node's answer for an aliased name is already the
@@ -720,6 +930,23 @@ function isBare(request) {
720
930
  return !(request.startsWith(".") || path.isAbsolute(request) || request.startsWith("file:"));
721
931
  }
722
932
 
933
+ /**
934
+ * Whether Node accepts an `exports` target as a file in its package: `./` and then no
935
+ * empty, `.`, `..` or `node_modules` segment (PACKAGE_TARGET_RESOLVE). Node fails the
936
+ * import for any other, so no file is keyed for it.
937
+ */
938
+ function validTarget(target) {
939
+ return (
940
+ target.startsWith("./") &&
941
+ !target
942
+ .slice(2)
943
+ .split(/[\\/]/)
944
+ .some(
945
+ (seg) => seg === "" || seg === "." || seg === ".." || seg.toLowerCase() === "node_modules",
946
+ )
947
+ );
948
+ }
949
+
723
950
  /**
724
951
  * Node's real path for `request` from `parent` (the require hooks' resolver included), the
725
952
  * same call `state.resolve` makes, or null when Node cannot resolve it.
@@ -868,6 +1095,16 @@ function nearestNamedPackage(file) {
868
1095
  }
869
1096
  }
870
1097
  const packageDirs = new Map();
1098
+
1099
+ /**
1100
+ * The copy of a package `file` is in, as `{ dir, name }`: the installed package after its
1101
+ * last `node_modules/`, or else the nearest manifest that names one, as a workspace or
1102
+ * `file:` dependency is at its real path. Null when neither applies.
1103
+ */
1104
+ function copyOf(file) {
1105
+ const name = owningPackageOfFile(file);
1106
+ return name === null ? nearestNamedPackage(file) : { dir: installedPackageDirOf(file), name };
1107
+ }
871
1108
  /** Test seam: the package directory a mock's file and a request's file are compared by. */
872
1109
  export const _packageDirOf = packageDirOf;
873
1110
 
@@ -979,8 +1216,8 @@ function vitestMockFor(index, request, parent, filename) {
979
1216
  * result (Vitest caches it on the entry), an automock's mocked exports, or the module
980
1217
  * a `__mocks__` redirect evaluated. R9: one that cannot be had synchronously fails by name.
981
1218
  */
982
- const FACTORY_NOT_SETTLED =
983
- "its factory is async and has not settled; import the module in the test first";
1219
+ // The reason only: mockNotSeenByNode gives the advice.
1220
+ const FACTORY_NOT_SETTLED = "its factory is async and has not settled";
984
1221
  /** Manual-mock entries whose factory returned a promise that has not settled. */
985
1222
  const settlingFactories = new WeakSet();
986
1223
 
@@ -1119,6 +1356,111 @@ function mockNotSeenByNode(request, parent, reason) {
1119
1356
  }
1120
1357
  const reportedNotSeen = new Set();
1121
1358
 
1359
+ /** Record that `entry` was served to a `require` in `file`. */
1360
+ function servedTo(state, file, entry) {
1361
+ const key = canonical(file);
1362
+ let entries = state.served.get(key);
1363
+ if (entries === undefined) state.served.set(key, (entries = new Set()));
1364
+ entries.add(entry);
1365
+ }
1366
+
1367
+ /**
1368
+ * A compiled module's call of an export it imported, as Babel (`(0, _core.name)`,
1369
+ * `new _core.Name()`) or tsc (`(0, core_1.name)`) writes it, that was not a function.
1370
+ */
1371
+ const IMPORTED_NOT_CALLABLE = /([\w$]+)\.([\w$]+)\)? is not a (?:function|constructor)\b/;
1372
+
1373
+ /** An import binding's name, or a module name, as one comparable word. */
1374
+ function bindingWord(name) {
1375
+ return name
1376
+ .replace(/^(?:_+|import_)/, "")
1377
+ .replace(/_?\d+$/, "")
1378
+ .replace(/[^A-Za-z0-9]/g, "")
1379
+ .toLowerCase();
1380
+ }
1381
+
1382
+ /** A file path or file URL, as a path. */
1383
+ function displayPath(file) {
1384
+ return file.startsWith("file:") ? fileURLToPath(file) : file;
1385
+ }
1386
+
1387
+ /** Errors a load step has looked at already (missingExportError). */
1388
+ const examinedErrors = new WeakSet();
1389
+
1390
+ /** ` (<file>)` for the `__mocks__` file whose exports are `value`, or "". */
1391
+ function manualMockFileOf(value) {
1392
+ for (const id of Object.keys(Module._cache)) {
1393
+ if (Module._cache[id]?.exports === value) return ` (${id})`;
1394
+ }
1395
+ return "";
1396
+ }
1397
+
1398
+ /**
1399
+ * The names compiled code may call a binding of `entry`'s module after: its spec, the
1400
+ * spec's last segment, and the mocked file's package and file name.
1401
+ */
1402
+ function namesOf(entry) {
1403
+ const names = [entry.spec, path.basename(entry.spec).replace(/\.[^.]*$/, "")];
1404
+ if (typeof entry.filename === "string") {
1405
+ const pkg = owningPackageOfFile(entry.filename);
1406
+ if (pkg !== null) names.push(pkg.split("/").at(-1) ?? pkg);
1407
+ names.push(path.basename(entry.filename).replace(/\.[^.]*$/, ""));
1408
+ }
1409
+ return names;
1410
+ }
1411
+
1412
+ /**
1413
+ * The named error for `error`, thrown while Node loaded `request` from `parent`, when the
1414
+ * module it loaded called an export that a mock it was served leaves out (#886), or null.
1415
+ * The mock is matched by the export's name and by the binding the compiled code reads
1416
+ * it through, which is named after the module (`_expoModulesCore`, `expo_modules_core_1`).
1417
+ * The export is not filled in: a factory's object is the whole module, as under Jest.
1418
+ */
1419
+ function missingExportError(state, error, request, parent) {
1420
+ if (!(error instanceof TypeError) || isVitestNativeError(error)) return null;
1421
+ // Only the innermost load an error passes through is the module whose code threw it:
1422
+ // an outer load that was served the same mock is not the one that called it.
1423
+ if (examinedErrors.has(error)) return null;
1424
+ examinedErrors.add(error);
1425
+ if (state.served.size === 0) return null;
1426
+ const match = IMPORTED_NOT_CALLABLE.exec(error.message);
1427
+ if (match === null) return null;
1428
+ const file = state.resolve(request, parent);
1429
+ const served = file === null ? undefined : state.served.get(file);
1430
+ if (served === undefined) return null;
1431
+ const [, binding, name] = match;
1432
+ const word = bindingWord(binding);
1433
+ // A mock jest.doMock replaced, or one served before jest.resetModules(), is no longer
1434
+ // the module's mock.
1435
+ const current = new Set(state.allEntries());
1436
+ for (const entry of served) {
1437
+ if (!current.has(entry)) continue;
1438
+ const value = entry.value;
1439
+ if (
1440
+ !entry.has ||
1441
+ value === null ||
1442
+ (typeof value !== "object" && typeof value !== "function")
1443
+ ) {
1444
+ continue;
1445
+ }
1446
+ if (name in value) continue;
1447
+ const spec = entry.spec;
1448
+ if (!namesOf(entry).some((named) => bindingWord(named) === word)) continue;
1449
+ const mock = entry.manual
1450
+ ? `the manual mock of '${spec}'${manualMockFileOf(value)}`
1451
+ : `the jest.mock('${spec}') factory${typeof entry.from === "string" ? ` in ${displayPath(entry.from)}` : ""}`;
1452
+ return new VitestNativeTypeError(
1453
+ "JEST_MOCK_MISSING_EXPORT",
1454
+ `${file} uses ${name} from '${spec}', which ${mock} does not export ` +
1455
+ `("${error.message}"). The mock is the whole module, as under Jest. Add ${name} ` +
1456
+ `to the mock, or build it on the real module: ` +
1457
+ `jest.mock('${spec}', () => ({ ...jest.requireActual('${spec}'), … })).`,
1458
+ { cause: error },
1459
+ );
1460
+ }
1461
+ return null;
1462
+ }
1463
+
1122
1464
  /**
1123
1465
  * Whether a relative require that landed on `filename`, mocked for a whole package
1124
1466
  * (`jest.mock('react-native-reanimated', …)`), is the package reaching its own entry as
@@ -1143,109 +1485,119 @@ function isPackageOwnRelativeLoad(entry, request, filename, parentFile) {
1143
1485
 
1144
1486
  function installLoadHook(state) {
1145
1487
  // The outermost load step (LOAD_STEPS): a per-file mock beats a preset and the registry.
1146
- nodeDispatch().load.add(
1147
- "mocks",
1148
- (next) =>
1149
- function (request, parent, ...rest) {
1150
- // A project file is what a test or a Node-loaded project module requires. Only
1151
- // those requests can share Vite's instances; any request can hit a mock, but
1152
- // only when there is one.
1153
- const fromProject =
1154
- typeof parent?.filename === "string" &&
1155
- !NODE_MODULES.test(parent.filename) &&
1156
- state.isResettable(parent.filename);
1157
- if (Module.isBuiltin(request)) return next(request, parent, ...rest);
1158
- // A hot worker keeps React, its renderers, scheduler and RNTL for its whole life. A
1159
- // require they make is answered once and kept, so a file's mock would stay theirs
1160
- // in every later file: RNTL first loaded in a file that mocks react-native as
1161
- // `{ Platform }` read StyleSheet.flatten from that mock in later files' fireEvent
1162
- // (#670). They get the actual module; the file's own code still gets its mock.
1163
- // Per file, and under hotRuntime.freshRuntime, they load again in every file, and
1164
- // see its mocks as under Jest.
1165
- if (
1166
- globalThis.__vitest_native_hot_reset &&
1167
- typeof parent?.filename === "string" &&
1168
- isRuntimeResidentFile(parent.filename)
1169
- ) {
1170
- return next(request, parent, ...rest);
1171
- }
1172
- const viMocks = nodeMocks && !madeByVitest(parent?.filename) ? vitestMocks() : null;
1173
- const pendingMocks = nodeMocks && !madeByVitest(parent?.filename) && pendingCount() > 0;
1174
- // A jest.mock this request can reach (mayIntercept), or a vi.mock: otherwise the
1175
- // request is Node's, and only a project file goes further.
1176
- const mockable = state.mayIntercept(request, parent);
1177
- if (!fromProject && !mockable && viMocks === null && !pendingMocks) {
1488
+ nodeDispatch().load.add("mocks", (next) => {
1489
+ const load = function (request, parent, ...rest) {
1490
+ // A project file is what a test or a Node-loaded project module requires. Only
1491
+ // those requests can share Vite's instances; any request can hit a mock, but
1492
+ // only when there is one.
1493
+ const fromProject =
1494
+ typeof parent?.filename === "string" &&
1495
+ !NODE_MODULES.test(parent.filename) &&
1496
+ state.isResettable(parent.filename);
1497
+ if (Module.isBuiltin(request)) return next(request, parent, ...rest);
1498
+ // A hot worker keeps React, its renderers, scheduler and RNTL for its whole life. A
1499
+ // require they make is answered once and kept, so a file's mock would stay theirs
1500
+ // in every later file: RNTL first loaded in a file that mocks react-native as
1501
+ // `{ Platform }` read StyleSheet.flatten from that mock in later files' fireEvent
1502
+ // (#670). They get the actual module; the file's own code still gets its mock.
1503
+ // Per file, and under hotRuntime.freshRuntime, they load again in every file, and
1504
+ // see its mocks as under Jest.
1505
+ if (
1506
+ globalThis.__vitest_native_hot_reset &&
1507
+ typeof parent?.filename === "string" &&
1508
+ isRuntimeResidentFile(parent.filename)
1509
+ ) {
1510
+ return next(request, parent, ...rest);
1511
+ }
1512
+ const viMocks = nodeMocks && !madeByVitest(parent?.filename) ? vitestMocks() : null;
1513
+ const pendingMocks = nodeMocks && !madeByVitest(parent?.filename) && pendingCount() > 0;
1514
+ // A jest.mock this request can reach (mayIntercept), or a vi.mock: otherwise the
1515
+ // request is Node's, and only a project file goes further.
1516
+ const mockable = state.mayIntercept(request, parent);
1517
+ if (!fromProject && !mockable && viMocks === null && !pendingMocks) {
1518
+ return next(request, parent, ...rest);
1519
+ }
1520
+ // A jest.mock (this registry) is matched first, then a vi.mock (Vitest's). R8:
1521
+ // jest.requireActual's own load is never a vi.mock either; it takes the path
1522
+ // below, whose lookup gives it the real module.
1523
+ const actualLoad =
1524
+ state.bypass !== null &&
1525
+ state.bypass === (state.resolve(request, parent) ?? `\0${request}`);
1526
+ // No jest.mock this request can reach (an empty registry, or one holding only
1527
+ // other packages' registrations, such as a library's own Jest setup): a vi.mock
1528
+ // decides first.
1529
+ if (!mockable && !actualLoad && (viMocks !== null || pendingMocks)) {
1530
+ const served = serveVitestMock(viMocks, pendingMocks, request, parent, () =>
1531
+ state.resolve(request, parent),
1532
+ );
1533
+ if (served !== NONE) return served;
1534
+ // R10: a request no mock matched is Node's, as it was with no mocks at all.
1535
+ if (!fromProject) return next(request, parent, ...rest);
1536
+ }
1537
+ // With no mock it can reach, only a project file can be served from Vite. For a bare specifier,
1538
+ // Node's own answer decides: a file under node_modules goes to Node's loader as is;
1539
+ // anything else (a workspace link to source, a package's self-reference, an alias the
1540
+ // hooks apply) is resolved as below, reusing that answer.
1541
+ if (!mockable && isBare(request)) {
1542
+ const resolved = nodeResolution(request, parent);
1543
+ if (resolved !== null && NODE_MODULES.test(resolved)) {
1544
+ state.stats.toNode++;
1178
1545
  return next(request, parent, ...rest);
1179
1546
  }
1180
- // A jest.mock (this registry) is matched first, then a vi.mock (Vitest's). R8:
1181
- // jest.requireActual's own load is never a vi.mock either; it takes the path
1182
- // below, whose lookup gives it the real module.
1183
- const actualLoad =
1184
- state.bypass !== null &&
1185
- state.bypass === (state.resolve(request, parent) ?? `\0${request}`);
1186
- // No jest.mock this request can reach (an empty registry, or one holding only
1187
- // other packages' registrations, such as a library's own Jest setup): a vi.mock
1188
- // decides first.
1189
- if (!mockable && !actualLoad && (viMocks !== null || pendingMocks)) {
1190
- const served = serveVitestMock(viMocks, pendingMocks, request, parent, () =>
1191
- state.resolve(request, parent),
1192
- );
1193
- if (served !== NONE) return served;
1194
- // R10: a request no mock matched is Node's, as it was with no mocks at all.
1195
- if (!fromProject) return next(request, parent, ...rest);
1196
- }
1197
- // With no mock it can reach, only a project file can be served from Vite. For a bare specifier,
1198
- // Node's own answer decides: a file under node_modules goes to Node's loader as is;
1199
- // anything else (a workspace link to source, a package's self-reference, an alias the
1200
- // hooks apply) is resolved as below, reusing that answer.
1201
- if (!mockable && isBare(request)) {
1202
- const resolved = nodeResolution(request, parent);
1203
- if (resolved !== null && NODE_MODULES.test(resolved)) {
1204
- state.stats.toNode++;
1205
- return next(request, parent, ...rest);
1206
- }
1207
- if (resolved !== null) state.resolutions.set(`${parent.filename}\0${request}`, resolved);
1208
- }
1209
- const filename = state.resolve(request, parent);
1210
- const entry = state.lookup(filename, request);
1211
- // R8: requireActual's load is the real module, past a vi.mock too; it may still
1212
- // share Vite's instance of a project file below, as before.
1213
- const bypassed = entry === BYPASSED || isExecutingManualMock(entry);
1214
- // A package reaching its own entry relatively, mocked for the whole package, is
1215
- // the real module, as under Jest (isPackageOwnRelativeLoad): no mock serves it.
1216
- const ownRelative =
1217
- entry !== undefined &&
1218
- !bypassed &&
1219
- isPackageOwnRelativeLoad(entry, request, filename, parent?.filename);
1220
- if (entry !== undefined && !bypassed && !ownRelative) return state.valueOf(entry);
1221
- if (!bypassed && !ownRelative && !state.isEmpty() && (viMocks !== null || pendingMocks)) {
1222
- const served = serveVitestMock(viMocks, pendingMocks, request, parent, () => filename);
1223
- if (served !== NONE) return served;
1224
- }
1225
- // A module Node already holds stays the one `require` returns: switching a later
1226
- // require to Vite's copy would change its identity mid-file.
1227
- if (
1228
- fromProject &&
1229
- filename !== null &&
1230
- !state.isolation &&
1231
- !NODE_MODULES.test(filename) &&
1232
- Module._cache[filename] === undefined
1233
- ) {
1234
- // experimental.ownershipModel 'resolution': a file Vite owns is Vite's instance in
1235
- // either load order, evaluated now if Vite has not (native/bridge.mjs). Nothing is
1236
- // put in Module._cache: the next require asks Vite's map again, as this one did. It
1237
- // answers first: it also refuses a module Vite holds that it must not serve (one
1238
- // whose evaluation threw, or one still being evaluated).
1239
- if (bridging) {
1240
- const bridged = bridgedInstanceOf(filename, parent);
1241
- if (bridged !== NONE) return bridged;
1242
- }
1243
- const shared = viteInstanceOf(filename);
1244
- if (shared !== NONE) return shared;
1547
+ if (resolved !== null) state.resolutions.set(`${parent.filename}\0${request}`, resolved);
1548
+ }
1549
+ const filename = state.resolve(request, parent);
1550
+ const entry = state.lookup(filename, request);
1551
+ // R8: requireActual's load is the real module, past a vi.mock too; it may still
1552
+ // share Vite's instance of a project file below, as before.
1553
+ const bypassed = entry === BYPASSED || isExecutingManualMock(entry);
1554
+ // A package reaching its own entry relatively, mocked for the whole package, is
1555
+ // the real module, as under Jest (isPackageOwnRelativeLoad): no mock serves it.
1556
+ const ownRelative =
1557
+ entry !== undefined &&
1558
+ !bypassed &&
1559
+ isPackageOwnRelativeLoad(entry, request, filename, parent?.filename);
1560
+ if (entry !== undefined && !bypassed && !ownRelative) {
1561
+ if (typeof parent?.filename === "string") servedTo(state, parent.filename, entry);
1562
+ return state.valueOf(entry);
1563
+ }
1564
+ if (!bypassed && !ownRelative && !state.isEmpty() && (viMocks !== null || pendingMocks)) {
1565
+ const served = serveVitestMock(viMocks, pendingMocks, request, parent, () => filename);
1566
+ if (served !== NONE) return served;
1567
+ }
1568
+ // A module Node already holds stays the one `require` returns: switching a later
1569
+ // require to Vite's copy would change its identity mid-file.
1570
+ if (
1571
+ fromProject &&
1572
+ filename !== null &&
1573
+ !state.isolation &&
1574
+ !NODE_MODULES.test(filename) &&
1575
+ Module._cache[filename] === undefined
1576
+ ) {
1577
+ // experimental.ownershipModel 'resolution': a file Vite owns is Vite's instance in
1578
+ // either load order, evaluated now if Vite has not (native/bridge.mjs). Nothing is
1579
+ // put in Module._cache: the next require asks Vite's map again, as this one did. It
1580
+ // answers first: it also refuses a module Vite holds that it must not serve (one
1581
+ // whose evaluation threw, or one still being evaluated).
1582
+ if (bridging) {
1583
+ const bridged = bridgedInstanceOf(filename, parent);
1584
+ if (bridged !== NONE) return bridged;
1245
1585
  }
1246
- return next(request, parent, ...rest);
1247
- },
1248
- );
1586
+ const shared = viteInstanceOf(filename);
1587
+ if (shared !== NONE) return shared;
1588
+ }
1589
+ return next(request, parent, ...rest);
1590
+ };
1591
+ // A module that throws while it loads, because a mock it was served lacks an export
1592
+ // it uses, fails naming the mock (#886). Anything else is rethrown as it was.
1593
+ return function (request, parent, ...rest) {
1594
+ try {
1595
+ return load(request, parent, ...rest);
1596
+ } catch (error) {
1597
+ throw missingExportError(state, error, request, parent) ?? error;
1598
+ }
1599
+ };
1600
+ });
1249
1601
 
1250
1602
  // The precompiled React Native registry requires its own modules by id, past
1251
1603
  // Module._load (see registry.mjs). Jest serves `jest.mock('react-native/Libraries/
@@ -1254,7 +1606,7 @@ function installLoadHook(state) {
1254
1606
  Object.defineProperty(globalThis, "__vitest_native_node_mock_for", {
1255
1607
  configurable: true,
1256
1608
  get: () =>
1257
- state.entries.size === 0 && (!nodeMocks || (!vitestHasMocks() && pendingCount() === 0))
1609
+ state.isEmpty() && (!nodeMocks || (!vitestHasMocks() && pendingCount() === 0))
1258
1610
  ? undefined
1259
1611
  : nodeMockForRegistry,
1260
1612
  });
@@ -1263,7 +1615,10 @@ function installLoadHook(state) {
1263
1615
  * and the file it is in, for isPackageOwnRelativeLoad, as through Node's loader.
1264
1616
  */
1265
1617
  function nodeMockForRegistry(filename, request, parentFile) {
1266
- const entry = state.lookup(canonical(filename), filename);
1618
+ const entry = state.lookup(
1619
+ canonical(filename),
1620
+ typeof request === "string" ? request : filename,
1621
+ );
1267
1622
  if (entry === BYPASSED || isExecutingManualMock(entry)) return NONE;
1268
1623
  if (entry !== undefined) {
1269
1624
  // The package's own relative load of its entry is the real module (as above).
@@ -1277,6 +1632,18 @@ function installLoadHook(state) {
1277
1632
  return mocked === undefined ? NONE : vitestMockValue(mocked, filename, null);
1278
1633
  }
1279
1634
  nodeMockForRegistry.NONE = NONE;
1635
+ /**
1636
+ * The mock for Node's ESM loader's load of `file` (a URL resolveMocked marked), or NONE.
1637
+ * An import cannot wait for a factory the author wrote async: its pending promise would
1638
+ * become an empty module, so it fails by name, as jestMockForImport does for the bridge.
1639
+ */
1640
+ nodeMockForRegistry.forImport = (file) => {
1641
+ const value = nodeMockForRegistry(file);
1642
+ if (Object.prototype.toString.call(value) === "[object Promise]") {
1643
+ throw mockNotSeenByNode(file, null, FACTORY_NOT_SETTLED);
1644
+ }
1645
+ return value;
1646
+ };
1280
1647
 
1281
1648
  // The mock seam of the require bridge (experimental.ownershipModel 'resolution',
1282
1649
  // native/bridge.mjs), which evaluates a Vite-owned module synchronously in Vite's place:
@@ -1359,7 +1726,8 @@ function installLoadHook(state) {
1359
1726
  nodeMockForRegistry.mayReach = (request, parentFile) => {
1360
1727
  if (!nodeMocks) return false;
1361
1728
  if (request.startsWith("file:")) request = fileOfUrl(request);
1362
- if (state.entries.size > 0 || pendingCount() > 0) return true;
1729
+ // A root mock a jest.unmock left by name only (byName) still reaches other copies.
1730
+ if (!state.isEmpty() || pendingCount() > 0) return true;
1363
1731
  const index = vitestMocks();
1364
1732
  return index !== null && mayReachMock(index, request, { filename: parentFile });
1365
1733
  };
@@ -1370,7 +1738,9 @@ function installLoadHook(state) {
1370
1738
  nodeMockForRegistry.markFor = (file, request, parentFile) => {
1371
1739
  if (!nodeMocks) return null;
1372
1740
  const parent = { filename: parentFile };
1373
- const jestEntry = state.entries.get(canonical(file));
1741
+ const jestEntry = state.entryOf(canonical(file), request);
1742
+ // A package's own relative import of a file a root mock covers is real (entryOf).
1743
+ if (jestEntry === BYPASSED) return null;
1374
1744
  if (jestEntry !== undefined) return markOf(jestEntry);
1375
1745
  if (pendingCount() > 0 && assertNoPendingMockOf(state, file, request, parent)) return null;
1376
1746
  const index = vitestMocks();