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
@@ -11,15 +11,20 @@
11
11
  // this entry) to rewrite top-level jest.mock/unmock/doMock to the hoisted vi.*
12
12
  // form at transform time. `jest.fn`, `jest.spyOn`, `jest.requireActual`,
13
13
  // `jest.useFakeTimers` work at runtime via the `jest` global installed here.
14
- import { expect, vi } from "vitest";
14
+ import { afterAll, beforeEach, expect, vi } from "vitest";
15
15
  import { createRequire } from "node:module";
16
16
  import path from "node:path";
17
17
  import { jestMockInterop } from "./interop.mjs";
18
18
  import { installJestObject } from "./jest-object.mjs";
19
+ import { docsUrl } from "../docs-url.mjs";
19
20
  import { callerFile } from "./caller.mjs";
20
21
  import { errorsWithMethodsEquality } from "./error-equality.mjs";
21
22
  import { VitestNativeError } from "../errors.mjs";
23
+ import { projectContext } from "../context.mjs";
22
24
  import { NODE_MOCKS_STATE_ID, actualExports, config, nodeRegistry } from "./node-registry.mjs";
25
+ import { nodeDispatch } from "../node-dispatch.mjs";
26
+ import { JEST_COMPAT_SHIM_FILES } from "./aliases.mjs";
27
+ import { fileURLToPath } from "node:url";
23
28
 
24
29
  // The global `require` below resolves from the consumer project root.
25
30
  const require = createRequire(path.join(config.projectRoot, "package.json"));
@@ -149,15 +154,14 @@ if (typeof vi.now !== "function") vi.now = () => Date.now();
149
154
  // "jest.isolateModules is not a function" TypeErrors deep in a migrated suite.
150
155
  // Give each one an error that names the API and states the closest migration,
151
156
  // so the failure is a signpost instead of a mystery.
152
- const MIGRATION_GUIDE =
153
- "https://github.com/danfry1/vitest-native/blob/main/packages/vitest-native/docs/migrating-from-jest.md";
157
+ const UNSUPPORTED_DOCS = docsUrl("/guide/errors#JEST_API_UNSUPPORTED");
154
158
  function unsupported(name, guidance) {
155
159
  if (typeof vi[name] === "function") return;
156
160
  vi[name] = () => {
157
161
  throw new VitestNativeError(
158
162
  "JEST_API_UNSUPPORTED",
159
163
  `jest.${name}() has no Vitest equivalent. ${guidance}`,
160
- { docs: MIGRATION_GUIDE },
164
+ { docs: UNSUPPORTED_DOCS },
161
165
  );
162
166
  };
163
167
  }
@@ -171,10 +175,6 @@ unsupported(
171
175
  );
172
176
  unsupported("deepUnmock", "Use vi.unmock()/vi.doUnmock() per module.");
173
177
  unsupported("unstable_mockModule", "Use vi.doMock(path, factory), which mocks ESM too.");
174
- unsupported(
175
- "replaceProperty",
176
- "Assign the property and restore it yourself, or use vi.spyOn(obj, key, 'get') for an accessor.",
177
- );
178
178
  // Vitest has no automocking at all, so these cannot be approximated — the whole
179
179
  // premise (every module auto-replaced with mocks) does not exist. Naming that is more
180
180
  // useful than a TypeError.
@@ -203,9 +203,117 @@ if (typeof vi.retryTimes !== "function") {
203
203
 
204
204
  // `vi`, with Jest's semantics for the mocks `jest.fn`/`jest.spyOn` create (see
205
205
  // jest-object.mjs). Everything else, including the members installed above, is `vi`.
206
- // The module-registry members are the `jest` object's own, not `vi`'s: `vi.resetModules`
207
- // keeps Vitest's meaning, and Vitest has no isolateModules to extend.
208
- globalThis.jest = installJestObject(vi, { resetModules, isolateModules, isolateModulesAsync });
206
+ // The module-registry members, replaceProperty and restoreAllMocks are the `jest` object's
207
+ // own, not `vi`'s: `vi.resetModules` and `vi.restoreAllMocks` keep Vitest's meaning, and
208
+ // Vitest has neither isolateModules nor replaceProperty to extend.
209
+ // `jest.replaceProperty(object, key, value)`, as jest-mock 29.7's ModuleMocker has it:
210
+ // the same checks and messages, the value assigned in place (the property stays a plain,
211
+ // writable value), and the returned `{ replaceValue, restore }`. A second replacement of
212
+ // the same property reuses the first, so restoring gives back the original. Restored by
213
+ // `restore()`, by `jest.restoreAllMocks()`, before each test where the project sets
214
+ // `restoreMocks` (as Jest's setting does; Vitest's restores only its own mocks), and when
215
+ // the test file ends, since Jest's next file has fresh modules and a reused worker
216
+ // (`isolate: false`, the hot runtime) keeps them. A bare `vi.restoreAllMocks()` leaves
217
+ // them, as it is Vitest's own.
218
+ const replacedProperties = new Set();
219
+ function typeOfValue(value) {
220
+ return value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
221
+ }
222
+ // jest-mock's own errors, as it throws them: a plain Error with Jest's message, which a
223
+ // suite written for Jest asserts on (Vitest's toThrow with an error instance compares the
224
+ // whole error, name included). The one place this file builds one.
225
+ function jestMockError(jestMessage) {
226
+ return new Error(jestMessage);
227
+ }
228
+ function replaceProperty(object, propertyKey, value) {
229
+ if (object == null || (typeof object !== "object" && typeof object !== "function")) {
230
+ throw jestMockError(
231
+ `Cannot use replaceProperty on a primitive value; ${typeOfValue(object)} given`,
232
+ );
233
+ }
234
+ if (propertyKey == null) throw jestMockError("No property name supplied");
235
+ const name = String(propertyKey);
236
+ let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey);
237
+ for (let proto = Object.getPrototypeOf(object); !descriptor && proto !== null;) {
238
+ descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey);
239
+ proto = Object.getPrototypeOf(proto);
240
+ }
241
+ if (!descriptor)
242
+ throw jestMockError(`Property \`${name}\` does not exist in the provided object`);
243
+ if (!descriptor.configurable) {
244
+ throw jestMockError(`Property \`${name}\` is not declared configurable`);
245
+ }
246
+ if (descriptor.get !== undefined) {
247
+ throw jestMockError(
248
+ `Cannot replace the \`${name}\` property because it has a getter. Use \`jest.spyOn(object, '${name}', 'get').mockReturnValue(value)\` instead.`,
249
+ );
250
+ }
251
+ if (descriptor.set !== undefined) {
252
+ throw jestMockError(
253
+ `Cannot replace the \`${name}\` property because it has a setter. Use \`jest.spyOn(object, '${name}', 'set').mockReturnValue(value)\` instead.`,
254
+ );
255
+ }
256
+ if (typeof descriptor.value === "function") {
257
+ throw jestMockError(
258
+ `Cannot replace the \`${name}\` property because it is a function. Use \`jest.spyOn(object, '${name}')\` instead.`,
259
+ );
260
+ }
261
+ for (const entry of replacedProperties) {
262
+ if (entry.object === object && entry.property === propertyKey) {
263
+ return entry.replaced.replaceValue(value);
264
+ }
265
+ }
266
+ const isPropertyOwner = Object.prototype.hasOwnProperty.call(object, propertyKey);
267
+ const originalValue = descriptor.value;
268
+ const entry = {
269
+ object,
270
+ property: propertyKey,
271
+ restore() {
272
+ if (isPropertyOwner) object[propertyKey] = originalValue;
273
+ else delete object[propertyKey];
274
+ },
275
+ replaced: {
276
+ replaceValue(next) {
277
+ object[propertyKey] = next;
278
+ return entry.replaced;
279
+ },
280
+ restore() {
281
+ entry.restore();
282
+ replacedProperties.delete(entry);
283
+ },
284
+ },
285
+ };
286
+ // Recorded only once the assignment has worked: a property that is configurable but
287
+ // not writable throws here, and an entry for it would throw again on every restore.
288
+ entry.replaced.replaceValue(value);
289
+ replacedProperties.add(entry);
290
+ return entry.replaced;
291
+ }
292
+ function restoreReplacedProperties() {
293
+ // Cleared first, so one restore that throws does not leave the others to throw again.
294
+ const entries = [...replacedProperties];
295
+ replacedProperties.clear();
296
+ for (const entry of entries) entry.restore();
297
+ }
298
+ /** `jest.restoreAllMocks()`: replaced properties, then Vitest's mocks, which run regardless. */
299
+ function restoreAllMocks() {
300
+ try {
301
+ restoreReplacedProperties();
302
+ } finally {
303
+ vi.restoreAllMocks();
304
+ }
305
+ return globalThis.jest;
306
+ }
307
+ if (projectContext()?.restoreMocks === true) beforeEach(restoreReplacedProperties);
308
+ afterAll(restoreReplacedProperties);
309
+
310
+ globalThis.jest = installJestObject(vi, {
311
+ resetModules,
312
+ isolateModules,
313
+ isolateModulesAsync,
314
+ replaceProperty,
315
+ restoreAllMocks,
316
+ });
209
317
 
210
318
  // Two identical errors whose class assigns methods as instance fields (zod 3's
211
319
  // ZodError) are never equal under Vitest, which compares an error's own properties and
@@ -262,12 +370,24 @@ if (typeof globalThis.__vnInteropMock !== "function") globalThis.__vnInteropMock
262
370
  // A factory's `jest.requireActual` of project source that jestMockTransform moved to
263
371
  // `vi.importActual` (transform.ts) gets its result in the shape requireActual gives.
264
372
  globalThis.__vnActualExports = actualExports;
373
+ // A factory's own `require` of project source, moved to Vite the same way: the value of
374
+ // the jest.mock factory registered for that file if there is one, as Jest's registry
375
+ // serves it, else the module as the factory's own `import()` loads it (`load`, so the
376
+ // specifier resolves from the test file and Vitest's other mocks apply), in the shape
377
+ // `require` gives.
378
+ globalThis.__vnFactoryRequire = async (from, spec, load) => {
379
+ const filename = registry.resolveFrom(spec, from);
380
+ const entry =
381
+ filename !== null ? registry.entries.get(filename) : registry.unresolved.get(spec);
382
+ if (entry) return registry.valueForImport(entry);
383
+ return actualExports(await load());
384
+ };
265
385
  globalThis.__vnJestUnmock = (from, spec) => registry.unregister(from, spec);
266
386
  // Registrations are per test file, as in Jest. This file evaluates before each test
267
387
  // file, so a worker reused without the hot runtime (`isolate: false`, or a watch
268
388
  // rerun of the same file) starts each one empty here. The hot runtime clears them at
269
389
  // the file boundary instead, through its state manifest, which verifies it did.
270
- if (!globalThis.__vitest_native_hot_reset) registry.clear();
390
+ if (!globalThis.__vitest_native_hot_reset) registry.clear({ keepLibrary: true });
271
391
  // Hot runtime: cleared at the file boundary and verified empty (state-manifest.mjs).
272
392
  globalThis.__vitest_native_register_state?.({
273
393
  id: NODE_MOCKS_STATE_ID,
@@ -318,3 +438,76 @@ async function isolateModulesAsync(fn) {
318
438
  // test modules have no `require` binding, so provide a global one resolved from the
319
439
  // project root. Guarded so it never clobbers an existing CJS `require`.
320
440
  if (typeof globalThis.require !== "function") globalThis.require = require;
441
+
442
+ // A require() of a package jest-compat replaces gets the shim (JEST_COMPAT_SHIM_FILES, files
443
+ // beside this one), as an import does through
444
+ // the same alias. The package itself throws when loaded outside Jest ("Do not import
445
+ // `@jest/globals` outside of the Jest test environment"), so the installed one is never
446
+ // the answer, for a test file, a project module or a library alike; this is unlike the
447
+ // project's other aliases, which apply in Node only where Node finds nothing
448
+ // (native/hooks.mjs).
449
+ const shimFiles = new Map();
450
+ nodeDispatch().load.add(
451
+ "jestCompatShims",
452
+ (next) =>
453
+ function (request, parent, ...rest) {
454
+ if (typeof request !== "string" || request.startsWith(".") || path.isAbsolute(request)) {
455
+ return next(request, parent, ...rest);
456
+ }
457
+ let file = shimFiles.get(request);
458
+ if (file === undefined) {
459
+ const target = JEST_COMPAT_SHIM_FILES[config.expandAlias(request)];
460
+ file = target ? fileURLToPath(new URL(target, import.meta.url)) : null;
461
+ shimFiles.set(request, file);
462
+ }
463
+ return next(file ?? request, parent, ...rest);
464
+ },
465
+ );
466
+
467
+ // `View.prototype`, as React Native's Jest preset has it: its stand-in for View is a
468
+ // class with the native methods (measure, measureInWindow, measureLayout, setNativeProps,
469
+ // focus, blur) on the prototype, so suites spy on them there
470
+ // (`jest.spyOn(View.prototype, 'measure')`) and read them at load
471
+ // (`Object.getOwnPropertyDescriptor(View.prototype, ...)`). React Native's own View has no
472
+ // prototype.
473
+ //
474
+ // The prototype given is the native methods object of the native engine's host class for
475
+ // RCTView (src/native/boundary.mjs): one class per view name, whose methods delegate to
476
+ // that object, so a spy on it reaches every View ref. A plain object, not the class's
477
+ // prototype, which would make React construct the component as a class. Under the mock
478
+ // engine, whose registry has no such class, nothing is set. Only here, in the
479
+ // Jest-semantics layer: the engine itself keeps React Native's View as it is.
480
+ //
481
+ // View only: every test that renders React Native loads View anyway, while setting Text's
482
+ // and ScrollView's here would load them, and their graphs, in every test file (63 and 142
483
+ // React Native modules against View's 19; tests-native/rn-facade-cost.test.ts). Exposing
484
+ // those lazily, once something loads them, is a follow-up.
485
+ function exposeNativeMethods() {
486
+ const reactNative = require("react-native");
487
+ const { get } = require("react-native/Libraries/NativeComponent/NativeComponentRegistry");
488
+ for (const [component, viewName] of [["View", "RCTView"]]) {
489
+ const target = reactNative[component];
490
+ if (target == null) continue;
491
+ // No prototype (a forwardRef object, an arrow function), or an ordinary function's
492
+ // untouched one; never a class's or one someone has already filled.
493
+ const own = target.prototype;
494
+ const replaceable =
495
+ own === undefined ||
496
+ (!own.isReactComponent &&
497
+ Object.getOwnPropertyNames(own).every((key) => key === "constructor"));
498
+ if (!replaceable) continue;
499
+ const methods = typeof get === "function" ? get(viewName)?.nativeMethods : undefined;
500
+ if (methods == null || typeof methods.measure !== "function") continue;
501
+ // An ordinary function's own prototype is writable but not configurable.
502
+ if (own === undefined) {
503
+ Object.defineProperty(target, "prototype", {
504
+ value: methods,
505
+ configurable: true,
506
+ writable: true,
507
+ });
508
+ } else {
509
+ target.prototype = methods;
510
+ }
511
+ }
512
+ }
513
+ exposeNativeMethods();