vitest-native 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +1063 -0
  2. package/README.md +47 -2
  3. package/dist/cli.cjs +642 -0
  4. package/dist/cli.d.cts +4 -0
  5. package/dist/cli.d.mts +4 -0
  6. package/dist/cli.mjs +638 -0
  7. package/dist/ecosystem-CO5vqExO.mjs +318 -0
  8. package/dist/ecosystem-IuZ-Gv0R.cjs +356 -0
  9. package/dist/errors-Dm5yLNTF.mjs +64 -0
  10. package/dist/errors-flXDIeWk.cjs +75 -0
  11. package/dist/errors.d.mts +46 -0
  12. package/dist/errors.mjs +78 -0
  13. package/dist/helpers.cjs +6 -23
  14. package/dist/helpers.d.cts +0 -6
  15. package/dist/helpers.d.mts +0 -6
  16. package/dist/helpers.mjs +6 -23
  17. package/dist/{index-vlK4zxuK.d.mts → index-BJL4cQ-l.d.cts} +22 -7
  18. package/dist/{index-YjjYELG7.d.cts → index-CvCU0cLl.d.mts} +20 -9
  19. package/dist/index.d.mts +8 -6
  20. package/dist/index.mjs +563 -232
  21. package/dist/jest-compat/interop.mjs +15 -0
  22. package/dist/jest-compat/setup.mjs +164 -5
  23. package/dist/matchers.cjs +16 -7
  24. package/dist/matchers.mjs +16 -7
  25. package/dist/native/boundary.mjs +108 -30
  26. package/dist/native/compile-cache.mjs +10 -5
  27. package/dist/native/explain.mjs +69 -0
  28. package/dist/native/hooks.mjs +151 -4
  29. package/dist/native/loader.mjs +61 -12
  30. package/dist/native/match.mjs +107 -8
  31. package/dist/native/module-reset.mjs +63 -0
  32. package/dist/native/registry.mjs +540 -0
  33. package/dist/native/reset.mjs +18 -12
  34. package/dist/native/resolve.d.mts +22 -0
  35. package/dist/native/resolve.mjs +21 -13
  36. package/dist/native/runner.mjs +34 -7
  37. package/dist/native/setup.mjs +19 -3
  38. package/dist/native/transform.mjs +195 -21
  39. package/dist/native/worker.mjs +69 -17
  40. package/dist/pool-Bcxp4Qrg.mjs +118 -0
  41. package/dist/pool-CFND7plG.cjs +122 -0
  42. package/dist/{preset-map-DCWaM08s.mjs → preset-map-BpDG_D5m.mjs} +1 -1
  43. package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-DxilQ4pI.cjs} +1 -1
  44. package/dist/{presets-7eMfp7o2.cjs → presets-BGTqVH6C.cjs} +227 -52
  45. package/dist/{presets-23FJ76O4.mjs → presets-CK85x8ey.mjs} +222 -53
  46. package/dist/presets.d.mts +2 -2
  47. package/dist/presets.mjs +2 -2
  48. package/dist/rntl-matchers.d.ts +35 -0
  49. package/dist/serializer.cjs +33 -3
  50. package/dist/serializer.mjs +33 -3
  51. package/dist/setup.mjs +544 -193
  52. package/docs/hot-default-design.md +129 -0
  53. package/docs/migrating-from-jest.md +43 -7
  54. package/docs/migrating-from-vitest-react-native.md +1 -1
  55. package/docs/release-readiness.md +24 -6
  56. package/docs/versioning.md +133 -0
  57. package/package.json +40 -38
  58. package/dist/index.cjs +0 -643
  59. package/dist/index.d.cts +0 -14
  60. package/dist/pool-B7LBfcMQ.mjs +0 -67
  61. package/dist/pool-p54QV1dQ.cjs +0 -69
  62. package/dist/presets.cjs +0 -17
  63. package/dist/presets.d.cts +0 -2
  64. package/dist/setup.cjs +0 -2514
  65. package/dist/setup.d.cts +0 -1
@@ -16,6 +16,21 @@
16
16
  // returns (those with `__esModule` or an explicit `default`) untouched.
17
17
  export function jestMockInterop(mod) {
18
18
  if (mod == null) return mod;
19
+ // An async factory — or any factory returning a promise — resolves to the module
20
+ // shape, so interop applies to the resolved value. Vitest awaits a factory result,
21
+ // so handing the promise back is enough. Without this the promise itself fell into
22
+ // the object branch below, where it has no own enumerable keys and no `default`,
23
+ // producing `{ default: Promise }`: every named export vanished and Vitest reported
24
+ // `No "x" export is defined on the mock` about a vi.mock the author never wrote.
25
+ //
26
+ // Tested by tag rather than by a `then` method: a module may legitimately export a
27
+ // function named `then`, and awaiting that calls it with (resolve, reject) and never
28
+ // settles — a hung test file, which is worse than the bug this fixes. The tag holds
29
+ // for native promises from any realm, and `async` functions and `Promise.resolve`
30
+ // only ever produce those.
31
+ if (Object.prototype.toString.call(mod) === "[object Promise]") {
32
+ return mod.then(jestMockInterop);
33
+ }
19
34
  const t = typeof mod;
20
35
  if (t === "object" || t === "function") {
21
36
  // Already ES-shaped — respect the author's/real module's default export.
@@ -13,19 +13,100 @@
13
13
  // `jest.useFakeTimers` work at runtime via the `jest` global installed here.
14
14
  import { vi } from "vitest";
15
15
  import { createRequire } from "node:module";
16
+ import { fileURLToPath } from "node:url";
16
17
  import path from "node:path";
17
18
  import { jestMockInterop } from "./interop.mjs";
19
+ import { VitestNativeError } from "../errors.mjs";
18
20
 
19
21
  // Resolve modules from the consumer project root, not this file's location, so
20
22
  // `jest.requireActual('some-project-dep')` resolves the same module the suite sees.
21
23
  const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
22
24
  const require = createRequire(path.join(projectRoot, "package.json"));
23
25
 
24
- if (typeof vi.requireActual !== "function") vi.requireActual = (m) => require(m);
25
- if (typeof vi.requireMock !== "function") vi.requireMock = (m) => require(m);
26
- // `jest.setTimeout(ms)` has no global `vi` equivalent — no-op so suites that call
27
- // it at top level don't crash.
28
- if (typeof vi.setTimeout !== "function") vi.setTimeout = () => {};
26
+ // Real Jest suites commonly clone-and-override React Native:
27
+ // const RN = jest.requireActual('react-native'); RN.Platform = {...}; return RN
28
+ // Under the native engine RN's index is a CJS facade of lazy getters with no
29
+ // setters (see loader.mjs), so assigning to it throws "Cannot set property … which
30
+ // has only a getter" and takes the whole test file down at load. Jest's module is
31
+ // mutable, so match that: wrap the RN facade in a write-through proxy — reads fall
32
+ // through (keeping the getters lazy), writes are captured in an overlay so the
33
+ // override wins on later reads. Only `react-native` needs this; its submodules and
34
+ // other packages are ordinary mutable CJS.
35
+ function writableModuleFacade(mod) {
36
+ if (mod == null || typeof mod !== "object") return mod;
37
+ const overrides = new Map();
38
+ return new Proxy(mod, {
39
+ get: (target, prop) => (overrides.has(prop) ? overrides.get(prop) : Reflect.get(target, prop)),
40
+ set: (_target, prop, value) => {
41
+ overrides.set(prop, value);
42
+ return true;
43
+ },
44
+ has: (target, prop) => overrides.has(prop) || Reflect.has(target, prop),
45
+ });
46
+ }
47
+
48
+ /**
49
+ * The file that called into here, taken from the stack.
50
+ *
51
+ * Jest resolves a relative `requireActual('../x')` against the CALLING module. This
52
+ * shim had a single require anchored at the project root, so bare specifiers worked
53
+ * and relative ones escaped the source tree: `jest.requireActual('../thing')` threw
54
+ * MODULE_NOT_FOUND with a requireStack pointing at <projectRoot>/package.json, which
55
+ * is a confusing place to be sent when the file sits next to the test.
56
+ *
57
+ * The stack is the only thing that knows the caller. These are plain runtime calls
58
+ * on the `jest` global, not rewritten at transform time, so there is no import.meta
59
+ * to consult.
60
+ */
61
+ function callerFile() {
62
+ const original = Error.prepareStackTrace;
63
+ try {
64
+ Error.prepareStackTrace = (_, frames) => frames;
65
+ const frames = new Error().stack;
66
+ for (const frame of frames) {
67
+ const file = typeof frame.getFileName === "function" ? frame.getFileName() : null;
68
+ if (!file || file.startsWith("node:") || file.includes("/jest-compat/")) continue;
69
+ return file.startsWith("file://") ? fileURLToPath(file) : file;
70
+ }
71
+ } catch {
72
+ // Fall through to the project-root require below.
73
+ } finally {
74
+ Error.prepareStackTrace = original;
75
+ }
76
+ return null;
77
+ }
78
+
79
+ /** Resolve as Jest does: relative against the caller, bare from the project root. */
80
+ function requireFrom(specifier) {
81
+ if (typeof specifier === "string" && specifier.startsWith(".")) {
82
+ const caller = callerFile();
83
+ // A caller-relative miss is the honest answer. Falling back to the project root
84
+ // could resolve some other file that happens to sit at the same relative path.
85
+ if (caller) return createRequire(caller)(specifier);
86
+ }
87
+ return require(specifier);
88
+ }
89
+
90
+ if (typeof vi.requireActual !== "function")
91
+ vi.requireActual = (m) =>
92
+ m === "react-native" ? writableModuleFacade(require(m)) : requireFrom(m);
93
+ if (typeof vi.requireMock !== "function") vi.requireMock = (m) => requireFrom(m);
94
+ // `jest.setTimeout(ms)` maps onto `vi.setConfig({ testTimeout })`, which applies for
95
+ // the rest of the file — the same scope Jest gives it, since Vitest resets the config
96
+ // after each test file.
97
+ //
98
+ // This used to be a silent no-op, on the grounds that there was no `vi` equivalent.
99
+ // There is. The cost of the no-op was not a crash but silence: a suite opening with
100
+ // `jest.setTimeout(30000)`, which is routine for slower React Native suites, kept
101
+ // Vitest's 5s default and its slow tests failed on time while the line that was
102
+ // supposed to prevent that sat there looking effective.
103
+ if (typeof vi.setTimeout !== "function") {
104
+ vi.setTimeout = (ms) => {
105
+ if (typeof vi.setConfig === "function" && typeof ms === "number") {
106
+ vi.setConfig({ testTimeout: ms });
107
+ }
108
+ };
109
+ }
29
110
 
30
111
  // `jest.advanceTimersByTime(Async)` is lenient in Jest: when fake timers are NOT
31
112
  // active it's effectively a no-op. Vitest's `vi.advanceTimersByTimeAsync` instead
@@ -42,6 +123,84 @@ vi.advanceTimersByTime = (...args) =>
42
123
  vi.advanceTimersByTimeAsync = async (...args) =>
43
124
  vi.isFakeTimers() ? advanceTimersByTimeAsync(...args) : undefined;
44
125
 
126
+ // Jest APIs that DO have a Vitest equivalent, under a different name. Each of these
127
+ // was missing, so a suite calling it hit `jest.X is not a function` — the bare
128
+ // TypeError the signposting below exists to avoid — even though the behaviour was
129
+ // available all along. `dontMock` is the sibling of the already-signposted
130
+ // `deepUnmock`, which is what marks these as omissions rather than decisions.
131
+ if (typeof vi.dontMock !== "function") vi.dontMock = (m) => vi.doUnmock(m);
132
+ if (typeof vi.setMock !== "function") vi.setMock = (m, exports) => vi.doMock(m, () => exports);
133
+ // `Date.now()` alone is right for both clocks: Vitest's fake timers replace Date, so
134
+ // this returns the faked time when they are active and the real time otherwise —
135
+ // which is what jest.now() reports. An earlier version consulted
136
+ // vi.getMockedSystemTime() first; removing that branch changed no observable
137
+ // behaviour, so it was complexity no test could distinguish.
138
+ if (typeof vi.now !== "function") vi.now = () => Date.now();
139
+
140
+ // Jest APIs with NO Vitest equivalent would otherwise surface as bare
141
+ // "jest.isolateModules is not a function" TypeErrors deep in a migrated suite.
142
+ // Give each one an error that names the API and states the closest migration,
143
+ // so the failure is a signpost instead of a mystery.
144
+ const MIGRATION_GUIDE =
145
+ "https://github.com/danfry1/vitest-native/blob/main/packages/vitest-native/docs/migrating-from-jest.md";
146
+ function unsupported(name, guidance) {
147
+ if (typeof vi[name] === "function") return;
148
+ vi[name] = () => {
149
+ throw new VitestNativeError(
150
+ "JEST_API_UNSUPPORTED",
151
+ `jest.${name}() has no Vitest equivalent. ${guidance}`,
152
+ { docs: MIGRATION_GUIDE },
153
+ );
154
+ };
155
+ }
156
+ unsupported(
157
+ "isolateModules",
158
+ "Use vi.resetModules() plus a dynamic import() to get a fresh module copy.",
159
+ );
160
+ unsupported(
161
+ "createMockFromModule",
162
+ "Build the mock explicitly with vi.fn()/vi.mock(), or import the real module and override members.",
163
+ );
164
+ unsupported(
165
+ "genMockFromModule",
166
+ "Build the mock explicitly with vi.fn()/vi.mock(), or import the real module and override members.",
167
+ );
168
+ unsupported("deepUnmock", "Use vi.unmock()/vi.doUnmock() per module.");
169
+ unsupported(
170
+ "isolateModulesAsync",
171
+ "Use vi.resetModules() plus a dynamic import() to get a fresh module copy.",
172
+ );
173
+ 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
+ // Vitest has no automocking at all, so these cannot be approximated — the whole
179
+ // premise (every module auto-replaced with mocks) does not exist. Naming that is more
180
+ // useful than a TypeError.
181
+ for (const name of [
182
+ "enableAutomock",
183
+ "disableAutomock",
184
+ "autoMockOff",
185
+ "autoMockOn",
186
+ "onGenerateMock",
187
+ ]) {
188
+ unsupported(name, "Vitest has no automocking; mock each module explicitly with vi.mock().");
189
+ }
190
+ // jest.retryTimes configures retries at runtime; Vitest configures them statically.
191
+ // Warn once and continue — crashing a suite over retry policy helps nobody.
192
+ if (typeof vi.retryTimes !== "function") {
193
+ let warned = false;
194
+ vi.retryTimes = () => {
195
+ if (!warned) {
196
+ warned = true;
197
+ console.warn(
198
+ `[vitest-native] jest.retryTimes() is ignored under Vitest — set test.retry in your vitest config (or per-test: test('name', { retry: N }, fn)).`,
199
+ );
200
+ }
201
+ };
202
+ }
203
+
45
204
  globalThis.jest = vi;
46
205
 
47
206
  // jest.mock factories are wrapped by jestMockTransform to route their return
package/dist/matchers.cjs CHANGED
@@ -15,11 +15,20 @@ function getProps(received) {
15
15
  }
16
16
  return null;
17
17
  }
18
- function notAnElementResult(ctx, matcherName, received) {
19
- return {
20
- pass: false,
21
- message: () => `${ctx.utils.matcherHint(matcherName, "element", "expected")}\n\nExpected a rendered element with a \`props\` object, but received:\n ${ctx.utils.printReceived(received)}`
22
- };
18
+ /**
19
+ * THROWS for a value that is not a rendered element — it does not return
20
+ * `{ pass: false }`.
21
+ *
22
+ * Returning a failing result reads as the safe option and is not: under `.not` the
23
+ * result is inverted, so `expect(null).not.toHaveAnimatedStyle({ opacity: 1 })`
24
+ * SILENTLY PASSED. A query that matched nothing, or a value of the wrong shape, then
25
+ * produced a green assertion — the failure mode a matcher must never have.
26
+ *
27
+ * Throwing also matches React Native Testing Library, whose `checkHostElement` raises
28
+ * a HostElementTypeError for the same case rather than failing softly.
29
+ */
30
+ function throwNotAnElement(ctx, matcherName, received) {
31
+ throw new Error(`${ctx.utils.matcherHint(`${ctx.isNot ? ".not." : ""}${matcherName}`, "element", "expected")}\n\nExpected a rendered element with a \`props\` object, but received:\n ${ctx.utils.printReceived(received)}`);
23
32
  }
24
33
  /** Pick only the keys present in `expected` from `actual`, for readable diffs. */
25
34
  function subset(actual, expected) {
@@ -29,7 +38,7 @@ function subset(actual, expected) {
29
38
  }
30
39
  function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
31
40
  const props = getProps(received);
32
- if (!props) return notAnElementResult(this, "toHaveAnimatedStyle", received);
41
+ if (!props) throwNotAnElement(this, "toHaveAnimatedStyle", received);
33
42
  const currentStyle = flattenStyle(props.style);
34
43
  const compared = config.shouldMatchAllProps ? currentStyle : subset(currentStyle, expectedStyle);
35
44
  const pass = this.equals(compared, expectedStyle);
@@ -45,7 +54,7 @@ function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
45
54
  }
46
55
  function toHaveAnimatedProps(received, expectedProps) {
47
56
  const props = getProps(received);
48
- if (!props) return notAnElementResult(this, "toHaveAnimatedProps", received);
57
+ if (!props) throwNotAnElement(this, "toHaveAnimatedProps", received);
49
58
  const compared = subset(props.animatedProps && typeof props.animatedProps === "object" ? props.animatedProps : props, expectedProps);
50
59
  const pass = this.equals(compared, expectedProps);
51
60
  return {
package/dist/matchers.mjs CHANGED
@@ -14,11 +14,20 @@ function getProps(received) {
14
14
  }
15
15
  return null;
16
16
  }
17
- function notAnElementResult(ctx, matcherName, received) {
18
- return {
19
- pass: false,
20
- message: () => `${ctx.utils.matcherHint(matcherName, "element", "expected")}\n\nExpected a rendered element with a \`props\` object, but received:\n ${ctx.utils.printReceived(received)}`
21
- };
17
+ /**
18
+ * THROWS for a value that is not a rendered element — it does not return
19
+ * `{ pass: false }`.
20
+ *
21
+ * Returning a failing result reads as the safe option and is not: under `.not` the
22
+ * result is inverted, so `expect(null).not.toHaveAnimatedStyle({ opacity: 1 })`
23
+ * SILENTLY PASSED. A query that matched nothing, or a value of the wrong shape, then
24
+ * produced a green assertion — the failure mode a matcher must never have.
25
+ *
26
+ * Throwing also matches React Native Testing Library, whose `checkHostElement` raises
27
+ * a HostElementTypeError for the same case rather than failing softly.
28
+ */
29
+ function throwNotAnElement(ctx, matcherName, received) {
30
+ throw new Error(`${ctx.utils.matcherHint(`${ctx.isNot ? ".not." : ""}${matcherName}`, "element", "expected")}\n\nExpected a rendered element with a \`props\` object, but received:\n ${ctx.utils.printReceived(received)}`);
22
31
  }
23
32
  /** Pick only the keys present in `expected` from `actual`, for readable diffs. */
24
33
  function subset(actual, expected) {
@@ -28,7 +37,7 @@ function subset(actual, expected) {
28
37
  }
29
38
  function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
30
39
  const props = getProps(received);
31
- if (!props) return notAnElementResult(this, "toHaveAnimatedStyle", received);
40
+ if (!props) throwNotAnElement(this, "toHaveAnimatedStyle", received);
32
41
  const currentStyle = flattenStyle(props.style);
33
42
  const compared = config.shouldMatchAllProps ? currentStyle : subset(currentStyle, expectedStyle);
34
43
  const pass = this.equals(compared, expectedStyle);
@@ -44,7 +53,7 @@ function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
44
53
  }
45
54
  function toHaveAnimatedProps(received, expectedProps) {
46
55
  const props = getProps(received);
47
- if (!props) return notAnElementResult(this, "toHaveAnimatedProps", received);
56
+ if (!props) throwNotAnElement(this, "toHaveAnimatedProps", received);
48
57
  const compared = subset(props.animatedProps && typeof props.animatedProps === "object" ? props.animatedProps : props, expectedProps);
49
58
  const pass = this.equals(compared, expectedProps);
50
59
  return {
@@ -47,6 +47,23 @@ function deviceConstants(platform, reactNativeVersion) {
47
47
  doLeftAndRightSwapInRTL: true,
48
48
  localeIdentifier: "en_US",
49
49
  },
50
+ // RN's getDevServer (Libraries/Core/Devtools/getDevServer.js) reads
51
+ // SourceCode.getConstants().scriptURL and calls .match() on it — undefined
52
+ // there throws and takes the whole file down. Expo's async-require
53
+ // (messageSocket) pulls this in on any Expo-core-importing test. Provide a
54
+ // defined string so the lookup resolves instead of crashing.
55
+ //
56
+ // Deliberately a file:// (bundled/release) URL, NOT http(s): getDevServer only
57
+ // treats http(s) scriptURLs as a live server, so a file:// value keeps
58
+ // `bundleLoadedFromServer` false — tests run as if loaded from a bundle, not a
59
+ // Metro dev server. That stops RN internals (AssetSourceResolver,
60
+ // symbolicateStackTrace, DevTools) and third-party SDKs from believing they're
61
+ // connected to a packager and attempting real network I/O against localhost:8081.
62
+ // Mirrors RN's own jest mock, which keeps this flag off (scriptURL: null there,
63
+ // but null would re-introduce the .match crash, so we use a bundled URL).
64
+ SourceCode: {
65
+ scriptURL: "file:///index.bundle",
66
+ },
50
67
  };
51
68
  }
52
69
 
@@ -126,36 +143,73 @@ function turboStubSource(platform, version) {
126
143
  // (e.g. showShareActionSheetWithOptions(options, error, success)). For the latter,
127
144
  // the success callback is the LAST function arg.
128
145
  const __SUCCESS_LAST = new Set(["showShareActionSheetWithOptions"]);
129
- const turboStub = (name) => new Proxy({}, {
130
- get: (_t, p) => {
131
- if (p === "getConstants") return () => (__C[name] || {});
132
- if (p === "getColorScheme") {
133
- return () => getBoundaryState(name).colorScheme ?? "light";
134
- }
135
- if (p === "setColorScheme") {
136
- return (colorScheme) => {
137
- getBoundaryState(name).colorScheme =
138
- colorScheme === "unspecified" || colorScheme == null ? "light" : colorScheme;
139
- };
140
- }
141
- if (p === "addListener") return () => ({ remove: () => {} });
142
- if (p === "removeListeners") return () => {};
143
- return (...args) => {
144
- // Callback-style native methods resolve via a callback argument. Invoke the
145
- // success callback so JS Promises that wrap these settle instead of hanging.
146
- const fns = args.filter((a) => typeof a === "function");
147
- if (fns.length) {
148
- const cb = typeof p === "string" && __SUCCESS_LAST.has(p) ? fns[fns.length - 1] : fns[0];
149
- return cb(false);
150
- }
151
- // Promise-returning native methods must yield a Promise, not undefined.
152
- if (typeof p === "string" && Object.prototype.hasOwnProperty.call(__ASYNC, p)) {
153
- return Promise.resolve(__ASYNC[p]);
146
+ // Stubs are memoized per module name in the shared boundary state, so
147
+ // NativeModules.Foo === NativeModules.Foo === TurboModuleRegistry.get('Foo')
148
+ // (matching bridgeless RN, where NativeModules proxies TurboModuleRegistry).
149
+ // Methods are memoized as own properties of the proxy target on first read —
150
+ // identity-stable across reads, and explicit writes win, so
151
+ // vi.spyOn(NativeModules.Foo, 'method') records calls instead of silently
152
+ // landing on a throwaway object.
153
+ const turboStub = (name) => {
154
+ const state = getBoundaryState(name);
155
+ if (state.__stub) return state.__stub;
156
+ const target = {};
157
+ state.__stub = new Proxy(target, {
158
+ get: (t, p) => {
159
+ // Explicitly-set properties win (spies, manual overrides, memoized methods).
160
+ if (Object.prototype.hasOwnProperty.call(t, p)) return t[p];
161
+ let v;
162
+ if (p === "getConstants") v = () => (__C[name] || {});
163
+ else if (p === "getColorScheme") {
164
+ v = () => getBoundaryState(name).colorScheme ?? "light";
165
+ } else if (p === "setColorScheme") {
166
+ v = (colorScheme) => {
167
+ getBoundaryState(name).colorScheme =
168
+ colorScheme === "unspecified" || colorScheme == null ? "light" : colorScheme;
169
+ };
170
+ } else if (p === "addListener") v = () => ({ remove: () => {} });
171
+ else if (p === "removeListeners") v = () => {};
172
+ else {
173
+ v = (...args) => {
174
+ // Callback-style native methods resolve via a callback argument. Invoke the
175
+ // success callback so JS Promises that wrap these settle instead of hanging.
176
+ const fns = args.filter((a) => typeof a === "function");
177
+ if (fns.length) {
178
+ const cb = typeof p === "string" && __SUCCESS_LAST.has(p) ? fns[fns.length - 1] : fns[0];
179
+ return cb(false);
180
+ }
181
+ // Promise-returning native methods must yield a Promise, not undefined.
182
+ if (typeof p === "string" && Object.prototype.hasOwnProperty.call(__ASYNC, p)) {
183
+ return Promise.resolve(__ASYNC[p]);
184
+ }
185
+ return undefined;
186
+ };
154
187
  }
155
- return undefined;
156
- };
157
- },
158
- });
188
+ // defineProperty, not assignment: sloppy-mode \`t["__proto__"] = fn\`
189
+ // would invoke the inherited __proto__ SETTER and silently swap the
190
+ // target's prototype instead of memoizing.
191
+ Object.defineProperty(t, p, {
192
+ value: v,
193
+ writable: true,
194
+ enumerable: true,
195
+ configurable: true,
196
+ });
197
+ return v;
198
+ },
199
+ // Every property reads as a callable stub, so report them all as present —
200
+ // vi.spyOn refuses to spy on a property its \`in\` check can't see.
201
+ has: () => true,
202
+ });
203
+ // Hot runtime: clear per-file state (spies, memoized methods) between files
204
+ // via the surgical-reset registry, while keeping the stub's identity for
205
+ // resident libraries that captured a reference at import time. Under the
206
+ // default engine each file gets a fresh process, so this never fires.
207
+ const resets = globalThis.__vitest_native_resets || (globalThis.__vitest_native_resets = []);
208
+ resets.push(() => {
209
+ for (const k of Reflect.ownKeys(target)) delete target[k];
210
+ });
211
+ return state.__stub;
212
+ };
159
213
  `;
160
214
  }
161
215
 
@@ -258,9 +312,30 @@ export const BOUNDARY_SOURCES = {
258
312
 
259
313
  const SUFFIXES = Object.keys(BOUNDARY_SOURCES);
260
314
 
315
+ /**
316
+ * Expo modules whose only job is talking to a live dev server — an environment
317
+ * that doesn't exist under Node. `expo`'s Expo.fx requires messageSocket whenever
318
+ * `__DEV__ && globalThis.expo`, and the module throws at load time when the
319
+ * bundle wasn't served over HTTP ("Cannot create devtools websocket connections
320
+ * in embedded environments"), taking down any suite that imports an expo-*
321
+ * package. Stub it to a no-op, like Jest's dev-server layer mocks do. Matched
322
+ * for both the published build/ output and the src/ TS sources (some resolution
323
+ * paths reach src/), in plain and .native platform variants.
324
+ */
325
+ const EXPO_DEV_STUBS = {
326
+ "src/async-require/messageSocket.native.ts": "module.exports = {};",
327
+ "src/async-require/messageSocket.ts": "module.exports = {};",
328
+ "build/async-require/messageSocket.native.js": "module.exports = {};",
329
+ "build/async-require/messageSocket.js": "module.exports = {};",
330
+ };
331
+ const EXPO_SUFFIXES = Object.keys(EXPO_DEV_STUBS);
332
+
261
333
  /** Normalised-path test: is this a native-boundary module? */
262
334
  export function isBoundary(normPath) {
263
- return SUFFIXES.some((s) => normPath.endsWith("/react-native/" + s));
335
+ return (
336
+ SUFFIXES.some((s) => normPath.endsWith("/react-native/" + s)) ||
337
+ EXPO_SUFFIXES.some((s) => normPath.endsWith("/expo/" + s))
338
+ );
264
339
  }
265
340
 
266
341
  /** Returns the CJS source for a boundary module, or null if not a boundary. */
@@ -271,5 +346,8 @@ export function boundarySourceFor(normPath, platform = "ios", version = "0.0.0")
271
346
  return typeof source === "function" ? source(platform, version) : source;
272
347
  }
273
348
  }
349
+ for (const s of EXPO_SUFFIXES) {
350
+ if (normPath.endsWith("/expo/" + s)) return EXPO_DEV_STUBS[s];
351
+ }
274
352
  return null;
275
353
  }
@@ -14,22 +14,27 @@
14
14
  import nodeModule from "node:module";
15
15
  import os from "node:os";
16
16
  import path from "node:path";
17
+ import { cacheRootFor } from "./transform.mjs";
17
18
 
18
19
  let _enabled = false;
19
20
 
20
21
  /**
21
22
  * Enable Node's persistent V8 compile cache for this worker/thread. Idempotent and
22
- * guarded per realm. Colocated under the `vitest-native-cache` tmp prefix so it
23
- * shares the transform cache's lifecycle (cleared with it on a cold run, reused on
24
- * warm). Must be called before RN's modules are first compiled.
23
+ * guarded per realm. Colocated with the transform disk cache (the project's
24
+ * node_modules/.cache/vitest-native when available — persistent and CI-restorable —
25
+ * else tmpdir) so both caches share a lifecycle. Must be called before RN's modules
26
+ * are first compiled.
25
27
  */
26
- export function enableV8CompileCache() {
28
+ export function enableV8CompileCache(projectRoot) {
27
29
  if (_enabled) return;
28
30
  _enabled = true;
29
31
  const enable = nodeModule.enableCompileCache;
30
32
  if (typeof enable !== "function") return; // Node < 22.8: feature absent
31
33
  try {
32
- enable.call(nodeModule, path.join(os.tmpdir(), "vitest-native-cache-v8"));
34
+ const root = projectRoot
35
+ ? cacheRootFor(projectRoot)
36
+ : path.join(os.tmpdir(), "vitest-native-cache");
37
+ enable.call(nodeModule, path.join(root, "v8"));
33
38
  // No atomic-write handling needed (unlike the transform cache, which writes
34
39
  // executable source): Node CRC32-validates each compile-cache entry on read,
35
40
  // so a torn or raced write from concurrent workers is a cache miss and a
@@ -0,0 +1,69 @@
1
+ // Turns the native engine's two worst failure moments — a Babel crash while
2
+ // transforming a file, and Node choking on untranspiled JSX/Flow from an
3
+ // externalized package — into errors that name the package and say what to do.
4
+ // Pure functions; used by transform.mjs and hooks.mjs, unit-tested directly.
5
+
6
+ /** The npm package name owning `file`, from its deepest node_modules segment, or null. */
7
+ export function packageNameFromPath(file) {
8
+ const norm = String(file).replace(/\\/g, "/");
9
+ const idx = norm.lastIndexOf("/node_modules/");
10
+ if (idx === -1) return null;
11
+ const rest = norm.slice(idx + "/node_modules/".length);
12
+ const segs = rest.split("/");
13
+ if (!segs[0]) return null;
14
+ if (segs[0].startsWith("@")) return segs[1] ? `${segs[0]}/${segs[1]}` : segs[0];
15
+ return segs[0];
16
+ }
17
+
18
+ /**
19
+ * Decorate a Babel failure from transformRN with the file, platform, and owning
20
+ * package, preserving the original message (Babel's includes a code frame) and
21
+ * chaining the original error as `cause`.
22
+ */
23
+ export function decorateTransformError(err, file, platform) {
24
+ const pkg = packageNameFromPath(file);
25
+ const subject = pkg ? `'${pkg}' (${file})` : `${file}`;
26
+ const hint = pkg
27
+ ? `The React Native Babel preset could not parse this file from ${pkg}. ` +
28
+ `If this happens on a package you added to transform: [...], the package may ` +
29
+ `ship syntax the preset can't handle — please report it at ` +
30
+ `https://github.com/danfry1/vitest-native/issues with the error below.`
31
+ : `The React Native Babel preset could not parse this file.`;
32
+ const wrapped = new Error(
33
+ `[vitest-native] Failed to transform ${subject} for platform '${platform}'.\n` +
34
+ `${hint}\n\n${err && err.message ? err.message : String(err)}`,
35
+ { cause: err },
36
+ );
37
+ wrapped.name = err && err.name ? err.name : "Error";
38
+ return wrapped;
39
+ }
40
+
41
+ // Node's SyntaxError messages when it compiles untranspiled JSX / Flow / TS.
42
+ // "Unexpected token '<'" = JSX; "Unexpected identifier" / "Unexpected reserved
43
+ // word" commonly = type annotations or `import type`.
44
+ const UNTRANSPILED_SYNTAX =
45
+ /Unexpected token '?<'?|Unexpected identifier|Unexpected reserved word|Missing initializer in const|Unexpected token ':'/;
46
+
47
+ /**
48
+ * When Node throws a SyntaxError compiling a node_modules file that vitest-native
49
+ * did NOT transform, explain the (very common) real cause: the package ships
50
+ * untranspiled JSX/Flow/TS and needs to be added to `transform: [...]`.
51
+ * Returns a decorated error, or null when the failure doesn't match the pattern.
52
+ */
53
+ export function explainUntransformedSyntaxError(err, file) {
54
+ if (!err || err.name !== "SyntaxError") return null;
55
+ if (!UNTRANSPILED_SYNTAX.test(String(err.message))) return null;
56
+ const pkg = packageNameFromPath(file);
57
+ if (!pkg) return null;
58
+ const wrapped = new SyntaxError(
59
+ `[vitest-native] '${pkg}' shipped source Node can't run directly ` +
60
+ `(${err.message} in ${file}).\n` +
61
+ `This usually means the package publishes untranspiled JSX, Flow, or TypeScript. ` +
62
+ `Ask vitest-native to transform it:\n\n` +
63
+ ` reactNative({ transform: ['${pkg}'] })\n\n` +
64
+ `in your vitest config. See https://github.com/danfry1/vitest-native` +
65
+ `/blob/main/packages/vitest-native/docs/migrating-from-jest.md`,
66
+ { cause: err },
67
+ );
68
+ return wrapped;
69
+ }