vitest-native 0.4.0 → 0.5.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.
@@ -5,49 +5,71 @@
5
5
  // source, setup files. What it can NOT touch is state living in the worker's
6
6
  // resident Node require cache: React Native itself (externalized by design),
7
7
  // other externalized CJS deps, and our boundary mocks. This module covers that
8
- // gap with an import-phase/test-phase attribution model:
8
+ // gap with a boot-baseline + import-attribution model:
9
9
  //
10
- // THE ATTRIBUTION PROBLEM: a resident (externalized) library that lazily
11
- // initializes during a file's IMPORT phase creates globals/listeners exactly
12
- // once — tear those down and the library breaks for every later file, because
13
- // its module init never re-runs (found the hard way: deleting Storybook's
14
- // __STORYBOOK_ADDONS_PREVIEW registry made every later story render empty).
15
- // State created during the TEST phase, by contrast, is pollution to remove.
10
+ // THE ATTRIBUTION PROBLEM: top-level code in an app/test module re-runs for
11
+ // every file and must be cleaned, while a resident externalized dependency
12
+ // initializes only once and may need to retain its process-wide state. A
13
+ // blanket "bless everything created during import" policy confuses the two
14
+ // and leaks app globals, env mutations, and listeners across files.
16
15
  //
17
16
  // The split is observable: runner.mjs calls bless() from onBeforeRunFiles —
18
17
  // after the test module (and its resident deps) finished importing, before
19
- // any test runs. Everything present at bless() joins the baseline; everything
20
- // that appears after it is test-phase pollution, reset by hotReset() at the
21
- // NEXT file's setup. If bless() never fires (consumer overrode `runner`), the
22
- // attribution-dependent teardowns stay disarmed — fail-open to stock
23
- // isolate:false semantics rather than guessing.
18
+ // any test runs. Listener call sites inside node_modules are treated as
19
+ // resident import state; listeners created by app/test modules stay tracked
20
+ // and are removed at the NEXT file's setup. Globals and process.env always
21
+ // return to the worker boot baseline, with an explicit preserveGlobals escape
22
+ // hatch for external libraries that intentionally publish a global registry.
23
+ // If bless() never fires (consumer overrode `runner`), attribution-dependent
24
+ // teardowns stay disarmed — fail-open rather than guessing.
24
25
  //
25
26
  // Covered surfaces:
26
27
  // 1. RN event listeners — every NativeEventEmitter (AppState, Appearance,
27
28
  // Keyboard, …) delegates to the RCTDeviceEventEmitter singleton, so one
28
29
  // wrapped addListener tracks the whole RN JS event surface. Test-phase
29
- // subscriptions are removed via their own public subscription.remove();
30
- // import-phase subscriptions are blessed.
31
- // 2. RN module state with known mutation APIs (Dimensions.set) — restored
32
- // from a boot-time snapshot (value-restore: no attribution needed).
33
- // 2b. process.env — restored to the last bless() snapshot.
34
- // 3. RNTL trees left mounted — RNTL is resident too, so its auto-cleanup
35
- // afterEach (registered during the first file) never re-registers for
36
- // later files; cleanup() is called explicitly.
30
+ // subscriptions are removed via their own public subscription.remove().
31
+ // Only import-phase subscriptions owned by node_modules are blessed.
32
+ // 2. RN module state with known mutation APIs (Dimensions, Appearance) —
33
+ // restored from a boot-time snapshot (value-restore: no attribution needed).
34
+ // 2b. process.env — restored to the worker boot snapshot.
35
+ // 3. Vitest timers/global/env stubs — restored by setup.mjs before this reset.
37
36
  // 4. Boundary/preset mocks that registered callbacks in
38
37
  // globalThis.__vitest_native_resets (none are stateful today; the
39
38
  // registry is the extension point).
40
- // 5. globalThis keys added during the previous TEST phase — deleted. The
41
- // baseline starts at the first per-file call (after Vitest injected its
42
- // per-batch globals) and grows at every bless(). Mutations of
43
- // pre-existing keys are not restored (documented v1 limitation).
39
+ // 5. globalThis keys added by a file — deleted. The baseline starts at the
40
+ // first per-file call (after Vitest injected its per-batch globals) and
41
+ // never grows implicitly. Mutations of pre-existing keys are not restored
42
+ // (documented limitation).
44
43
  import { createRequire } from "node:module";
45
44
  import path from "node:path";
45
+ import { fileURLToPath } from "node:url";
46
46
 
47
47
  // Keys owned by the harness or this plugin — never deleted by the globals diff.
48
- const PRESERVED_GLOBALS = /^(__vitest|__VITEST|__coverage__|__VITE)/;
49
- // Vitest-managed env keys change per task; leave them alone.
50
- const ENV_PRESERVED = /^VITEST_/;
48
+ const HARNESS_GLOBALS = /^(__vitest_native_|__VITEST|__coverage__|__VITE)/;
49
+ // Vitest updates these scheduler-owned values between tasks.
50
+ const ENV_PRESERVED = new Set(["VITEST_POOL_ID", "VITEST_WORKER_ID"]);
51
+ const RESET_FILE = fileURLToPath(import.meta.url).replaceAll("\\", "/");
52
+ const DEFAULT_PRESERVED_GLOBALS = ["__STORYBOOK_ADDONS_PREVIEW"];
53
+
54
+ function isResidentImportListener(stack, projectRoot) {
55
+ const root = projectRoot.replaceAll("\\", "/").replace(/\/$/, "");
56
+ let sawExternalFrame = false;
57
+
58
+ for (const rawLine of stack.split("\n").slice(1)) {
59
+ const line = rawLine.replaceAll("\\", "/");
60
+ if (line.includes(RESET_FILE)) continue;
61
+ if (!line.includes(`${root}/`)) continue;
62
+ if (line.includes("/node_modules/")) {
63
+ sawExternalFrame = true;
64
+ continue;
65
+ }
66
+ // A project-owned frame means this listener was created by app/test code,
67
+ // even when the call passed through React Native internals.
68
+ return false;
69
+ }
70
+
71
+ return sawExternalFrame;
72
+ }
51
73
 
52
74
  /**
53
75
  * Called once at hot-worker boot, AFTER react-native has been preloaded and its
@@ -56,17 +78,20 @@ const ENV_PRESERVED = /^VITEST_/;
56
78
  * hotReset is invoked by setup.mjs at the top of every file; bless by
57
79
  * runner.mjs between a file's import phase and its first test.
58
80
  */
59
- export function installHotReset({ projectRoot, diagnostics }) {
81
+ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = [] }) {
60
82
  const req = createRequire(path.join(projectRoot, "package.json"));
61
83
  const RN = req("react-native");
84
+ const explicitlyPreserved = new Set([...DEFAULT_PRESERVED_GLOBALS, ...preserveGlobals]);
62
85
 
63
86
  // --- (1) Track listeners added to the RCTDeviceEventEmitter singleton ---
64
- const tracked = new Set();
87
+ const tracked = new Map();
65
88
  const emitter = RN.DeviceEventEmitter;
66
89
  const origAddListener = emitter.addListener.bind(emitter);
67
90
  emitter.addListener = (type, listener, context) => {
68
91
  const sub = origAddListener(type, listener, context);
69
- tracked.add(sub);
92
+ tracked.set(sub, {
93
+ residentImport: isResidentImportListener(new Error().stack || "", projectRoot),
94
+ });
70
95
  return sub;
71
96
  };
72
97
 
@@ -78,12 +103,16 @@ export function installHotReset({ projectRoot, diagnostics }) {
78
103
  screen: { ...RN.Dimensions.get("screen") },
79
104
  };
80
105
  } catch {}
106
+ let colorScheme = null;
107
+ try {
108
+ colorScheme = RN.Appearance.getColorScheme?.() ?? null;
109
+ } catch {}
81
110
 
82
- // --- (2b) process.env snapshot, refreshed at every bless() ---
83
- let envBaseline = { ...process.env };
111
+ // --- (2b) Fixed process.env worker-boot snapshot ---
112
+ const envBaseline = { ...process.env };
84
113
 
85
- // --- (5) globalThis baseline: starts at the first per-file call, grows at
86
- // every bless() ---
114
+ // --- (5) globalThis baseline: starts at the first per-file call and remains
115
+ // fixed. Explicitly preserved keys may join it at an import boundary. ---
87
116
  let globalBaseline = null;
88
117
 
89
118
  // Attribution-dependent teardowns run only once bless() has fired at least
@@ -93,11 +122,15 @@ export function installHotReset({ projectRoot, diagnostics }) {
93
122
  function bless() {
94
123
  armed = true;
95
124
  if (globalBaseline) {
96
- for (const key of Reflect.ownKeys(globalThis)) globalBaseline.add(key);
125
+ for (const key of explicitlyPreserved) {
126
+ if (Object.hasOwn(globalThis, key)) globalBaseline.add(key);
127
+ }
128
+ }
129
+ // Resident external dependencies do not re-run, so retain only listeners
130
+ // whose import-time call stack belongs exclusively to node_modules.
131
+ for (const [sub, record] of tracked) {
132
+ if (record.residentImport) tracked.delete(sub);
97
133
  }
98
- envBaseline = { ...process.env };
99
- // Import-phase subscriptions are legitimate resident state — stop tracking.
100
- tracked.clear();
101
134
  }
102
135
 
103
136
  function hotReset() {
@@ -120,6 +153,9 @@ export function installHotReset({ projectRoot, diagnostics }) {
120
153
  RN.Dimensions.set(dims);
121
154
  } catch {}
122
155
  }
156
+ try {
157
+ RN.Appearance.setColorScheme?.(colorScheme);
158
+ } catch {}
123
159
 
124
160
  // (4) Boundary/preset mock reset callbacks.
125
161
  const resets = globalThis.__vitest_native_resets;
@@ -134,28 +170,28 @@ export function installHotReset({ projectRoot, diagnostics }) {
134
170
  if (!armed) return; // no bless yet → cannot attribute; fail open
135
171
 
136
172
  // (1) Remove the previous file's test-phase RN event listeners.
137
- for (const sub of tracked) {
173
+ for (const sub of tracked.keys()) {
138
174
  try {
139
175
  sub.remove();
140
176
  } catch {}
141
177
  }
142
178
  tracked.clear();
143
179
 
144
- // (2b) Restore process.env to the last bless() snapshot.
180
+ // (2b) Restore process.env to the worker boot snapshot.
145
181
  for (const key of Object.keys(process.env)) {
146
- if (ENV_PRESERVED.test(key)) continue;
182
+ if (ENV_PRESERVED.has(key)) continue;
147
183
  if (!(key in envBaseline)) delete process.env[key];
148
184
  else if (process.env[key] !== envBaseline[key]) process.env[key] = envBaseline[key];
149
185
  }
150
186
  for (const key of Object.keys(envBaseline)) {
151
- if (!(key in process.env) && !ENV_PRESERVED.test(key)) process.env[key] = envBaseline[key];
187
+ if (!(key in process.env) && !ENV_PRESERVED.has(key)) process.env[key] = envBaseline[key];
152
188
  }
153
189
 
154
190
  // (5) Delete globals added during the previous test phase.
155
191
  const deleted = [];
156
192
  for (const key of Reflect.ownKeys(globalThis)) {
157
193
  if (globalBaseline.has(key)) continue;
158
- if (typeof key === "string" && PRESERVED_GLOBALS.test(key)) continue;
194
+ if (typeof key === "string" && HARNESS_GLOBALS.test(key)) continue;
159
195
  try {
160
196
  delete globalThis[key];
161
197
  if (diagnostics) deleted.push(String(key));
@@ -1,20 +1,38 @@
1
- // Metro-style platform-extension resolution: prefer .ios.js / .native.js over .js,
2
- // and fall back to a directory index. Shared by the require hook and the loader.
1
+ // Metro-style platform-extension resolution: prefer the configured platform,
2
+ // then .native, then generic TS/JS variants, and fall back to a directory index.
3
+ // Shared by the require hook and the loader.
3
4
  import fs from "node:fs";
4
5
  import path from "node:path";
5
6
 
6
- const EXTS = [".ios.js", ".native.js", ".js"];
7
+ function extensionsFor(platform) {
8
+ const suffix = platform === "android" ? "android" : "ios";
9
+ return [
10
+ `.${suffix}.tsx`,
11
+ `.${suffix}.ts`,
12
+ `.${suffix}.jsx`,
13
+ `.${suffix}.js`,
14
+ ".native.tsx",
15
+ ".native.ts",
16
+ ".native.jsx",
17
+ ".native.js",
18
+ ".tsx",
19
+ ".ts",
20
+ ".jsx",
21
+ ".js",
22
+ ];
23
+ }
7
24
 
8
25
  /**
9
26
  * Given an absolute base path with no extension (e.g. ".../Foo"), return the
10
- * first existing platform variant (".../Foo.ios.js", etc.) or directory index,
27
+ * first existing platform variant (".../Foo.ios.tsx", etc.) or directory index,
11
28
  * or null if none exist.
12
29
  */
13
- export function resolvePlatformFile(absBase) {
14
- for (const ext of EXTS) {
30
+ export function resolvePlatformFile(absBase, platform = "ios") {
31
+ const extensions = extensionsFor(platform);
32
+ for (const ext of extensions) {
15
33
  if (fs.existsSync(absBase + ext)) return absBase + ext;
16
34
  }
17
- for (const ext of EXTS) {
35
+ for (const ext of extensions) {
18
36
  const idx = path.join(absBase, "index" + ext);
19
37
  if (fs.existsSync(idx)) return idx;
20
38
  }
@@ -7,6 +7,8 @@ import { expect, vi } from "vitest";
7
7
  import { installGlobals } from "./globals.mjs";
8
8
  import { installRequireHooks } from "./hooks.mjs";
9
9
  import * as presetFactories from "../presets.mjs";
10
+ import { animatedMatchers } from "../matchers.mjs";
11
+ import { serializer as rnSerializer } from "../serializer.mjs";
10
12
 
11
13
  // Hot runtime: surgical reset of state left by the PREVIOUS file. Setup files
12
14
  // are force-inlined by Vitest, so this body re-runs per test file even when the
@@ -35,6 +37,8 @@ if (globalThis.__vitest_native_hot_reset) {
35
37
 
36
38
  const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
37
39
  const diagnostics = process.env.VITEST_NATIVE_DIAGNOSTICS === "true";
40
+ const platform = process.env.VITEST_NATIVE_PLATFORM === "android" ? "android" : "ios";
41
+ const reactNativeVersion = process.env.VITEST_NATIVE_RN_VERSION || "0.0.0";
38
42
  // Extra node_modules packages to transform (from the plugin's `transform` option).
39
43
  let transformPkgs = [];
40
44
  try {
@@ -79,6 +83,16 @@ for (const name of presetNames) {
79
83
  }
80
84
 
81
85
  installGlobals();
86
+ // RNTL 13+ auto-registers matchers through the global expect when imported.
87
+ // Expose Vitest's expect only when the consumer has not enabled globals.
88
+ if (typeof globalThis.expect === "undefined") {
89
+ Object.defineProperty(globalThis, "expect", {
90
+ configurable: true,
91
+ enumerable: false,
92
+ value: expect,
93
+ writable: true,
94
+ });
95
+ }
82
96
  // register() once per WORKER, not per file: under the hot runtime this setup
83
97
  // file re-evaluates per test file in a persistent worker, and re-registering
84
98
  // would stack a new loader-hook layer on every file. (installGlobals and
@@ -86,10 +100,10 @@ installGlobals();
86
100
  if (!globalThis.__vitest_native_loader_registered) {
87
101
  globalThis.__vitest_native_loader_registered = true;
88
102
  register("./loader.mjs", import.meta.url, {
89
- data: { projectRoot, transformPkgs, presetExports },
103
+ data: { projectRoot, platform, reactNativeVersion, transformPkgs, presetExports },
90
104
  });
91
105
  }
92
- installRequireHooks(projectRoot, transformPkgs);
106
+ installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion);
93
107
 
94
108
  // Build the mock objects now that the require hooks are installed (preset
95
109
  // factories may lazily resolve react-native at render time).
@@ -102,14 +116,82 @@ for (const { pkg, mod, presetName } of presetDefs) {
102
116
  }
103
117
  }
104
118
 
119
+ // --- Shared test-helper control surface ---
120
+ //
121
+ // Helpers should manipulate the real RN modules where that is coherent. Platform
122
+ // cannot be switched after module resolution: Platform.ios/Platform.android and
123
+ // every platform-specific import have already been selected, so setPlatform()
124
+ // reports a clear configuration error instead of creating a split-brain graph.
125
+ const req = createRequire(path.join(projectRoot, "package.json"));
126
+ const RN = req("react-native");
127
+ const initialDimensions = {
128
+ window: { ...RN.Dimensions.get("window") },
129
+ screen: { ...RN.Dimensions.get("screen") },
130
+ };
131
+ const initialColorScheme = RN.Appearance.getColorScheme?.() ?? "light";
132
+
133
+ function emitColorScheme(colorScheme) {
134
+ RN.Appearance.setColorScheme?.(colorScheme);
135
+ RN.DeviceEventEmitter.emit?.("appearanceChanged", { colorScheme });
136
+ }
137
+
138
+ g.__vitest_native_control = {
139
+ engine: "native",
140
+ setPlatform() {
141
+ throw new Error(
142
+ `[vitest-native] setPlatform() is only available with engine:'mock'. ` +
143
+ `The native engine selects platform files when the module graph loads. ` +
144
+ `Use reactNative({ platform: 'ios' | 'android' }) or separate Vitest projects.`,
145
+ );
146
+ },
147
+ setDimensions(dims) {
148
+ const next = { ...RN.Dimensions.get("window"), ...dims };
149
+ RN.Dimensions.set({ window: next, screen: next });
150
+ },
151
+ setColorScheme(colorScheme) {
152
+ emitColorScheme(colorScheme ?? "light");
153
+ },
154
+ mockNativeModule(name, implementation) {
155
+ g.__vitest_native_module_mocks[name] = implementation;
156
+ },
157
+ resetAllMocks() {
158
+ RN.Dimensions.set({
159
+ window: { ...initialDimensions.window },
160
+ screen: { ...initialDimensions.screen },
161
+ });
162
+ emitColorScheme(initialColorScheme);
163
+ for (const name of Object.keys(g.__vitest_native_module_mocks)) {
164
+ delete g.__vitest_native_module_mocks[name];
165
+ }
166
+ for (const presetMock of Object.values(g.__vitest_native_preset_mocks || {})) {
167
+ presetMock?._reset?.();
168
+ presetMock?._resetStore?.();
169
+ }
170
+ vi.clearAllMocks();
171
+ },
172
+ };
173
+
105
174
  // --- RNTL built-in matchers (toBeOnTheScreen, toBeDisabled, toHaveStyle, …) ---
106
175
  // The mock engine's setup registers these; the native engine must too, or
107
176
  // `engine:'native'` users have no jest-native/RNTL matchers (and a jest-compat
108
177
  // migration is worse off — jestCompatAliases no-ops its extend-expect on the
109
178
  // promise that vitest-native registers them). Caught by the differential cross-check.
110
179
  try {
111
- const req = createRequire(path.join(projectRoot, "package.json"));
112
- const matchers = req("@testing-library/react-native/build/matchers");
180
+ let matchers = null;
181
+ let lastError;
182
+ for (const moduleId of [
183
+ "@testing-library/react-native/matchers",
184
+ "@testing-library/react-native/build/matchers",
185
+ "@testing-library/react-native/dist/matchers",
186
+ ]) {
187
+ try {
188
+ matchers = req(moduleId);
189
+ break;
190
+ } catch (error) {
191
+ lastError = error;
192
+ }
193
+ }
194
+ if (!matchers) throw lastError;
113
195
  const fns = {};
114
196
  for (const [k, v] of Object.entries(matchers || {})) {
115
197
  if (typeof v === "function" && k !== "__esModule") fns[k] = v;
@@ -126,6 +208,9 @@ try {
126
208
  }
127
209
  }
128
210
 
211
+ expect.extend(animatedMatchers);
212
+ expect.addSnapshotSerializer(rnSerializer);
213
+
129
214
  // NOTE: the cosmetic React "update to LogBoxStateSubscription not wrapped in
130
215
  // act()" warning (which used to appear on every interaction) is fixed at the
131
216
  // source — the native boundary stubs LogBoxNotificationContainer (the dev UI
@@ -13,6 +13,7 @@ let _preset;
13
13
  let _cacheDir;
14
14
  let _writeSeq = 0;
15
15
  const mem = new Map();
16
+ const TRANSFORM_CACHE_VERSION = 2;
16
17
 
17
18
  function init(projectRoot) {
18
19
  if (_babel) return;
@@ -28,7 +29,11 @@ function init(projectRoot) {
28
29
  );
29
30
  }
30
31
  const presetVersion = req("@react-native/babel-preset/package.json").version;
31
- _cacheDir = path.join(os.tmpdir(), "vitest-native-cache", presetVersion);
32
+ _cacheDir = path.join(
33
+ os.tmpdir(),
34
+ "vitest-native-cache",
35
+ `${presetVersion}-v${TRANSFORM_CACHE_VERSION}`,
36
+ );
32
37
  fs.mkdirSync(_cacheDir, { recursive: true });
33
38
  }
34
39
 
@@ -38,29 +43,30 @@ export function isFlow(src) {
38
43
  }
39
44
 
40
45
  /** Transform an RN source file to runnable CJS. Cached in-memory + on disk. */
41
- export function transformRN(file, src, projectRoot) {
46
+ export function transformRN(file, src, projectRoot, platform = "ios") {
42
47
  init(projectRoot);
43
- const memHit = mem.get(file);
48
+ const st = fs.statSync(file);
49
+ const memKey = `${platform}\0${file}\0${st.mtimeMs}\0${st.size}`;
50
+ const memHit = mem.get(memKey);
44
51
  if (memHit !== undefined) return memHit;
45
52
 
46
- const st = fs.statSync(file);
47
53
  const key = crypto
48
54
  .createHash("sha1")
49
- .update(file + ":" + st.mtimeMs + ":" + st.size)
55
+ .update(platform + ":" + file + ":" + st.mtimeMs + ":" + st.size)
50
56
  .digest("hex");
51
57
  const cachePath = path.join(_cacheDir, key + ".js");
52
58
  try {
53
59
  const cached = fs.readFileSync(cachePath, "utf8");
54
- mem.set(file, cached);
60
+ mem.set(memKey, cached);
55
61
  return cached;
56
62
  } catch {}
57
63
 
58
64
  const out = _babel.transformSync(src, {
59
65
  filename: file,
60
- presets: [_preset],
66
+ presets: [[_preset, { disableStaticViewConfigsCodegen: true }]],
61
67
  babelrc: false,
62
68
  configFile: false,
63
- caller: { name: "metro", bundler: "metro", platform: "ios", supportsStaticESM: false },
69
+ caller: { name: "metro", bundler: "metro", platform, supportsStaticESM: false },
64
70
  }).code;
65
71
  // Atomic write: multiple worker threads may transform the same RN file
66
72
  // concurrently on a cold cache. Write to a unique temp file then rename
@@ -74,6 +80,6 @@ export function transformRN(file, src, projectRoot) {
74
80
  fs.rmSync(tmp, { force: true });
75
81
  } catch {}
76
82
  }
77
- mem.set(file, out);
83
+ mem.set(memKey, out);
78
84
  return out;
79
85
  }
@@ -23,11 +23,18 @@ if (isMainThread || !parentPort) {
23
23
 
24
24
  const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
25
25
  const diagnostics = process.env.VITEST_NATIVE_DIAGNOSTICS === "true";
26
+ const platform = process.env.VITEST_NATIVE_PLATFORM === "android" ? "android" : "ios";
27
+ const reactNativeVersion = process.env.VITEST_NATIVE_RN_VERSION || "0.0.0";
26
28
  let transformPkgs = [];
29
+ let preserveGlobals = [];
27
30
  try {
28
31
  if (process.env.VITEST_NATIVE_TRANSFORM)
29
32
  transformPkgs = JSON.parse(process.env.VITEST_NATIVE_TRANSFORM);
30
33
  } catch {}
34
+ try {
35
+ if (process.env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS)
36
+ preserveGlobals = JSON.parse(process.env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS);
37
+ } catch {}
31
38
 
32
39
  if (diagnostics) {
33
40
  // One line per worker boot: under a hot pool, N files sharing a worker print
@@ -41,7 +48,7 @@ if (diagnostics) {
41
48
  // listener tracking in reset.mjs, so RN's own boot state is preserved across
42
49
  // per-file resets rather than wrongly torn down with test pollution.
43
50
  installGlobals();
44
- installRequireHooks(projectRoot, transformPkgs);
51
+ installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion);
45
52
  try {
46
53
  const req = createRequire(path.join(projectRoot, "package.json"));
47
54
  const RN = req("react-native");
@@ -56,7 +63,6 @@ try {
56
63
  "Keyboard",
57
64
  "Linking",
58
65
  "I18nManager",
59
- "InteractionManager",
60
66
  "PixelRatio",
61
67
  "StyleSheet",
62
68
  ]) {
@@ -64,13 +70,19 @@ try {
64
70
  void RN[name];
65
71
  } catch {}
66
72
  }
73
+ // Appearance initializes its bridge listener only when getColorScheme() is
74
+ // first called. Do that before listener tracking starts so the resident RN
75
+ // listener is treated as worker boot state instead of test-file pollution.
76
+ try {
77
+ RN.Appearance.getColorScheme?.();
78
+ } catch {}
67
79
  } catch (error) {
68
80
  throw new Error(
69
81
  `[vitest-native] hot worker failed to preload react-native from ${projectRoot}: ${error?.message}`,
70
82
  { cause: error },
71
83
  );
72
84
  }
73
- const { hotReset, bless } = installHotReset({ projectRoot, diagnostics });
85
+ const { hotReset, bless } = installHotReset({ projectRoot, diagnostics, preserveGlobals });
74
86
  globalThis.__vitest_native_hot_reset = hotReset; // invoked by setup.mjs per file
75
87
  globalThis.__vitest_native_hot_bless = bless; // invoked by runner.mjs after each import phase
76
88
 
@@ -16,15 +16,18 @@ var NativePoolWorker = class extends ThreadsPoolWorker {
16
16
  environment;
17
17
  recycleAfterFiles;
18
18
  memoryLimit;
19
+ diagnostics;
19
20
  filesRun = 0;
20
21
  lastHeapUsed = 0;
21
22
  memoryListenerAttached = false;
23
+ batchWarningShown = false;
22
24
  constructor(options, native) {
23
25
  super(options);
24
26
  this.entrypoint = path.resolve(native.workerEntry);
25
27
  this.environment = options.environment;
26
28
  this.recycleAfterFiles = native.recycleAfterFiles ?? 0;
27
29
  this.memoryLimit = native.memoryLimit ?? 0;
30
+ this.diagnostics = native.diagnostics ?? false;
28
31
  this.reportMemory = this.memoryLimit > 0;
29
32
  }
30
33
  async start() {
@@ -37,7 +40,13 @@ var NativePoolWorker = class extends ThreadsPoolWorker {
37
40
  }
38
41
  }
39
42
  send(message) {
40
- if (message.type === "run" || message.type === "collect") this.filesRun += message.context.files.length;
43
+ if (message.type === "run" || message.type === "collect") {
44
+ if (this.diagnostics && !this.batchWarningShown && message.context.files.length > 1 && (this.recycleAfterFiles > 0 || this.memoryLimit > 0)) {
45
+ this.batchWarningShown = true;
46
+ console.warn(`[vitest-native] hot worker received a ${message.context.files.length}-file Vitest task; recycling thresholds apply after the task completes. Use more than one worker when strict per-file retirement is required.`);
47
+ }
48
+ this.filesRun += message.context.files.length;
49
+ }
41
50
  super.send(message);
42
51
  }
43
52
  canReuse(task) {
@@ -1,6 +1,6 @@
1
1
  const require_chunk = require("./chunk-CZWwpsFl.cjs");
2
2
  let node_path = require("node:path");
3
- node_path = require_chunk.__toESM(node_path);
3
+ node_path = require_chunk.__toESM(node_path, 1);
4
4
  let vitest_node = require("vitest/node");
5
5
  //#region src/native/pool.ts
6
6
  function deepEqual(a, b) {
@@ -18,15 +18,18 @@ var NativePoolWorker = class extends vitest_node.ThreadsPoolWorker {
18
18
  environment;
19
19
  recycleAfterFiles;
20
20
  memoryLimit;
21
+ diagnostics;
21
22
  filesRun = 0;
22
23
  lastHeapUsed = 0;
23
24
  memoryListenerAttached = false;
25
+ batchWarningShown = false;
24
26
  constructor(options, native) {
25
27
  super(options);
26
28
  this.entrypoint = node_path.default.resolve(native.workerEntry);
27
29
  this.environment = options.environment;
28
30
  this.recycleAfterFiles = native.recycleAfterFiles ?? 0;
29
31
  this.memoryLimit = native.memoryLimit ?? 0;
32
+ this.diagnostics = native.diagnostics ?? false;
30
33
  this.reportMemory = this.memoryLimit > 0;
31
34
  }
32
35
  async start() {
@@ -39,7 +42,13 @@ var NativePoolWorker = class extends vitest_node.ThreadsPoolWorker {
39
42
  }
40
43
  }
41
44
  send(message) {
42
- if (message.type === "run" || message.type === "collect") this.filesRun += message.context.files.length;
45
+ if (message.type === "run" || message.type === "collect") {
46
+ if (this.diagnostics && !this.batchWarningShown && message.context.files.length > 1 && (this.recycleAfterFiles > 0 || this.memoryLimit > 0)) {
47
+ this.batchWarningShown = true;
48
+ console.warn(`[vitest-native] hot worker received a ${message.context.files.length}-file Vitest task; recycling thresholds apply after the task completes. Use more than one worker when strict per-file retirement is required.`);
49
+ }
50
+ this.filesRun += message.context.files.length;
51
+ }
43
52
  super.send(message);
44
53
  }
45
54
  canReuse(task) {