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
@@ -1,3 +1,4 @@
1
+ import { t as placeSetupFiles } from "./setup-files-C6-77IIs.mjs";
1
2
  import { n as ignorePattern, r as packageOfRequest, t as findNodeModuleMocks } from "./root-mocks-DP95ncxD.mjs";
2
3
  import { createRequire, isBuiltin } from "node:module";
3
4
  import { fileURLToPath } from "node:url";
@@ -16,9 +17,58 @@ const WITH_FACTORY = /* @__PURE__ */ new Set(["mock", "doMock"]);
16
17
  const UNMOCK = /* @__PURE__ */ new Set(["unmock", "doUnmock"]);
17
18
  const TRANSFORMABLE = /\.(?:[cm]?[jt]sx?)$/;
18
19
  const HAS_JEST_MOCK = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
20
+ const NAMES_JEST = /\bjest\b/;
21
+ const NAMES_MOCK_METHOD = /\b(?:mock|unmock|doMock|doUnmock)\b(?!\s*\.)/;
22
+ const JEST_SOURCES = /* @__PURE__ */ new Set(["@jest/globals", "vitest-native/jest-compat/jest-globals"]);
19
23
  const SETUP = "__vn_jest_compat__";
20
- /** Prepended to a file whose mock factories use the setup. Exported for tests. */
21
- const SETUP_ACCESSOR = `const ${SETUP} = vi.hoisted(() => (name) => {\n if (typeof globalThis[name] === "function") return globalThis[name];\n throw Object.assign(new Error("[vitest-native] jest.mock() factories need the jest-compat setup, which this test run does not load. " +\n "Add jestCompatSetup from 'vitest-native/jest-compat' to test.setupFiles, ahead of any setup file that calls jest.mock()."),\n { name: "VitestNativeError", code: "JEST_COMPAT_SETUP_MISSING" });\n});\n`;
24
+ /** Prepended to a file whose mock factories use the setup, through `vi` named `vi`. */
25
+ function setupAccessor(vi) {
26
+ return `const ${SETUP} = ${vi}.hoisted(() => (name) => {\n if (typeof globalThis[name] === "function") return globalThis[name];\n throw Object.assign(new Error("[vitest-native] jest.mock() factories need the jest-compat setup, which this test run does not load. " +\n "Add jestCompatSetup from 'vitest-native/jest-compat' to test.setupFiles, ahead of any setup file that calls jest.mock()."),\n { name: "VitestNativeError", code: "JEST_COMPAT_SETUP_MISSING" });\n});\n`;
27
+ }
28
+ setupAccessor("vi");
29
+ const VITEST_NAMES = /* @__PURE__ */ new Set(["vi", "vitest"]);
30
+ /**
31
+ * The name the rewritten calls reach Vitest's `vi` by, and whether the file must import it.
32
+ *
33
+ * Vitest's hoister adds `import { vi } from "vitest"` itself only to a file that imports
34
+ * nothing from 'vitest'. A file that imports `test` and `expect` from there, under the
35
+ * default `globals: false`, otherwise reaches no `vi` at all (#818). So the transform
36
+ * binds the name itself, unless the file already imports it from 'vitest'.
37
+ *
38
+ * A name is taken where the transform writes it (`sites`, and the top level, where the
39
+ * hoisted calls go) when the file declares it there as anything but that import. Even
40
+ * Vitest's own object, destructured from a namespace (`const { vi } = vitestNs`), is not
41
+ * yet initialised when Vitest moves `vi.mock` above it. When `vi` is taken, the calls use
42
+ * `vitest`, the same object under its other name; when both are, the file fails by name.
43
+ */
44
+ function vitestName(ast, id, sites) {
45
+ const top = /* @__PURE__ */ new Map();
46
+ const note = (name, imported) => {
47
+ if (VITEST_NAMES.has(name)) top.set(name, (top.get(name) ?? true) && imported);
48
+ };
49
+ for (const statement of ast.body) {
50
+ if (statement.type !== "ImportDeclaration") continue;
51
+ for (const spec of statement.specifiers) {
52
+ const imported = spec.type === "ImportSpecifier" ? propertyName(spec.imported) : null;
53
+ note(spec.local.name, statement.source.value === "vitest" && (imported === "vi" || imported === "vitest"));
54
+ }
55
+ }
56
+ for (const name of [...varNames(ast), ...blockNames(ast.body)]) note(name, false);
57
+ for (const statement of ast.body) if (statement.type === "ExportDefaultDeclaration" && statement.declaration.id) note(statement.declaration.id.name, false);
58
+ const nested = /* @__PURE__ */ new Set();
59
+ visitScopes(ast, VITEST_NAMES, (node, shadows) => {
60
+ if (!sites.has(node)) return;
61
+ for (const name of VITEST_NAMES) if (shadows(name)) nested.add(name);
62
+ });
63
+ for (const name of ["vi", "vitest"]) {
64
+ if (nested.has(name) || top.get(name) === false) continue;
65
+ return {
66
+ name,
67
+ add: !top.has(name)
68
+ };
69
+ }
70
+ throw new VitestNativeError("JEST_MOCK_VI_UNAVAILABLE", `[vitest-native] jestMockTransform rewrites jest.mock() in ${id.split("?")[0]} to calls on Vitest's \`vi\` object, which Vitest hoists only as \`vi\` or \`vitest\` imported from 'vitest'. Where those calls run, this file binds both names to something other than that import. Import \`vi\` from 'vitest' by name, or rename the file's own \`vi\` or \`vitest\`.`);
71
+ }
22
72
  /**
23
73
  * Visit every node in an ESTree AST (depth-first), calling `fn` on each. Returning
24
74
  * `false` from `fn` skips that node's children.
@@ -34,6 +84,170 @@ function walk(node, fn) {
34
84
  } else if (child && typeof child.type === "string") walk(child, fn);
35
85
  }
36
86
  }
87
+ /** Whether `node` is a `require('<literal>')` of one of JEST_SOURCES. */
88
+ function jestSourceOf(node) {
89
+ const spec = node?.type === "CallExpression" ? requireSpec(node) : null;
90
+ return spec !== null && JEST_SOURCES.has(spec);
91
+ }
92
+ function propertyName(node) {
93
+ if (node?.type === "Identifier") return node.name;
94
+ if (node?.type === "Literal" && typeof node.value === "string") return node.value;
95
+ return null;
96
+ }
97
+ /** The names a declaration pattern binds. */
98
+ function patternNames(pattern, into = []) {
99
+ if (!pattern) return into;
100
+ if (pattern.type === "Identifier") into.push(pattern.name);
101
+ else if (pattern.type === "ObjectPattern") for (const property of pattern.properties) patternNames(property.type === "RestElement" ? property.argument : property.value, into);
102
+ else if (pattern.type === "ArrayPattern") for (const element of pattern.elements) patternNames(element, into);
103
+ else if (pattern.type === "AssignmentPattern") patternNames(pattern.left, into);
104
+ else if (pattern.type === "RestElement") patternNames(pattern.argument, into);
105
+ return into;
106
+ }
107
+ /** The `var` names a function body declares, outside its nested functions. */
108
+ function varNames(body) {
109
+ const found = [];
110
+ walk(body, (node) => {
111
+ if (FUNCTION.has(node.type) || node.type === "ClassBody") return false;
112
+ if (node.type === "VariableDeclaration" && node.kind === "var") for (const declarator of node.declarations) patternNames(declarator.id, found);
113
+ });
114
+ return found;
115
+ }
116
+ /** The names a block's own statements declare with let, const, class or function. */
117
+ function blockNames(statements) {
118
+ const found = [];
119
+ for (const statement of statements) {
120
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
121
+ if (declaration?.type === "VariableDeclaration" && declaration.kind !== "var") for (const declarator of declaration.declarations) patternNames(declarator.id, found);
122
+ else if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id) found.push(declaration.id.name);
123
+ }
124
+ return found;
125
+ }
126
+ /**
127
+ * The identifiers named in `watched` that a scope inside the Program declares again (a
128
+ * parameter, a local, a catch binding): those refer to the local, not to the
129
+ * Program-level binding of that name.
130
+ */
131
+ function shadowedIdentifiers(ast, watched) {
132
+ const shadowed = /* @__PURE__ */ new WeakSet();
133
+ visitScopes(ast, watched, (node, shadows) => {
134
+ if (node.type === "Identifier" && watched.has(node.name) && shadows(node.name)) shadowed.add(node);
135
+ });
136
+ return shadowed;
137
+ }
138
+ /**
139
+ * Visit every node, with `shadows(name)` telling whether a scope inside the Program that
140
+ * encloses it (the node's own included) declares that name, for the names in `watched`.
141
+ */
142
+ function visitScopes(ast, watched, fn) {
143
+ const scopes = [];
144
+ const shadows = (name) => scopes.some((names) => names.has(name));
145
+ const visit = (node) => {
146
+ if (!node || typeof node.type !== "string") return;
147
+ let scope = null;
148
+ if (FUNCTION.has(node.type)) {
149
+ const declared = node.params.flatMap((param) => patternNames(param));
150
+ if (node.type === "FunctionExpression" && node.id) declared.push(node.id.name);
151
+ if (node.body.type === "BlockStatement") declared.push(...varNames(node.body), ...blockNames(node.body.body));
152
+ scope = declared;
153
+ } else if (node.type === "BlockStatement" || node.type === "StaticBlock") scope = blockNames(node.body);
154
+ else if (node.type === "SwitchStatement") scope = blockNames(node.cases.flatMap((c) => c.consequent));
155
+ else if (node.type === "ClassExpression" && node.id) scope = [node.id.name];
156
+ else if (node.type === "CatchClause") scope = patternNames(node.param);
157
+ else if ((node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") && (node.init ?? node.left)?.type === "VariableDeclaration" && (node.init ?? node.left).kind !== "var") scope = (node.init ?? node.left).declarations.flatMap((d) => patternNames(d.id));
158
+ const pushed = scope !== null && scope.some((name) => watched.has(name));
159
+ if (pushed) scopes.push(new Set(scope));
160
+ fn(node, shadows);
161
+ for (const key in node) {
162
+ if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
163
+ const child = node[key];
164
+ if (Array.isArray(child)) for (const c of child) visit(c);
165
+ else if (child && typeof child.type === "string") visit(child);
166
+ }
167
+ if (pushed) scopes.pop();
168
+ };
169
+ visit(ast);
170
+ }
171
+ /**
172
+ * The file's jest bindings. A Program-level further name for a jest object (`const j =
173
+ * mockJest`) or for one of its hoisted methods (`const { mock } = jest`) that a mock call
174
+ * then goes through is one Jest would not hoist either, and this transform would leave
175
+ * unapplied without a word, so it fails, naming the binding and its line. A name a scope
176
+ * declares again, or that is reassigned, is not that binding and is left alone, and so is
177
+ * `requireActual` under any name: it is never hoisted and works at run time as it is.
178
+ */
179
+ function jestBindings(ast, code, id) {
180
+ const names = /* @__PURE__ */ new Set(["jest"]);
181
+ const namespaces = /* @__PURE__ */ new Set();
182
+ const program = ast.body.map((statement) => statement.type === "ExportNamedDeclaration" && statement.declaration ? statement.declaration : statement);
183
+ for (const statement of program) if (statement.type === "ImportDeclaration") {
184
+ const fromJest = JEST_SOURCES.has(statement.source.value);
185
+ for (const specifier of statement.specifiers) if (!fromJest) {
186
+ if (specifier.local.name === "jest") names.delete("jest");
187
+ } else if (specifier.type === "ImportNamespaceSpecifier") namespaces.add(specifier.local.name);
188
+ else if (specifier.type === "ImportSpecifier" && propertyName(specifier.imported) === "jest") names.add(specifier.local.name);
189
+ } else if (statement.type === "VariableDeclaration") for (const declarator of statement.declarations) {
190
+ const init = declarator.init;
191
+ if (!init) continue;
192
+ if (jestSourceOf(init)) {
193
+ if (declarator.id.type === "Identifier") namespaces.add(declarator.id.name);
194
+ else if (declarator.id.type === "ObjectPattern") {
195
+ for (const property of declarator.id.properties) if (property.type === "Property" && propertyName(property.key) === "jest" && property.value.type === "Identifier") names.add(property.value.name);
196
+ }
197
+ } else if (init.type === "MemberExpression" && jestSourceOf(init.object) && propertyName(init.property) === "jest" && declarator.id.type === "Identifier") names.add(declarator.id.name);
198
+ }
199
+ const aliases = /* @__PURE__ */ new Map();
200
+ const methodAliases = /* @__PURE__ */ new Map();
201
+ const plainJest = (node) => node?.type === "Identifier" && names.has(node.name) || node?.type === "MemberExpression" && node.object?.type === "Identifier" && namespaces.has(node.object.name) && propertyName(node.property) === "jest";
202
+ for (const statement of program) {
203
+ if (statement.type !== "VariableDeclaration") continue;
204
+ for (const declarator of statement.declarations) {
205
+ const [target, value] = [declarator.id, declarator.init];
206
+ if (!value) continue;
207
+ if (plainJest(value)) {
208
+ if (target.type === "Identifier" && !names.has(target.name)) aliases.set(target.name, declarator);
209
+ if (target.type === "ObjectPattern") for (const property of target.properties) {
210
+ const name = property.type === "Property" ? propertyName(property.key) : null;
211
+ if (name && HOISTABLE.has(name) && property.value.type === "Identifier") methodAliases.set(property.value.name, declarator);
212
+ }
213
+ } else if (value.type === "MemberExpression" && plainJest(value.object) && HOISTABLE.has(propertyName(value.property) ?? "") && target.type === "Identifier") methodAliases.set(target.name, declarator);
214
+ }
215
+ }
216
+ const watched = /* @__PURE__ */ new Set([
217
+ ...names,
218
+ ...namespaces,
219
+ ...aliases.keys(),
220
+ ...methodAliases.keys()
221
+ ]);
222
+ watched.delete("jest");
223
+ const shadowed = watched.size > 0 ? shadowedIdentifiers(ast, watched) : /* @__PURE__ */ new WeakSet();
224
+ const isJest = (node) => node?.type === "Identifier" && names.has(node.name) && (node.name === "jest" || !shadowed.has(node)) || node?.type === "MemberExpression" && node.object?.type === "Identifier" && namespaces.has(node.object.name) && !shadowed.has(node.object) && propertyName(node.property) === "jest" && (!node.computed || node.property.type === "Literal");
225
+ if (aliases.size === 0 && methodAliases.size === 0) return { isJest };
226
+ walk(ast, (node) => {
227
+ const target = node.type === "AssignmentExpression" ? node.left : node.type === "UpdateExpression" ? node.argument : null;
228
+ if (target?.type === "Identifier" && !shadowed.has(target)) {
229
+ aliases.delete(target.name);
230
+ methodAliases.delete(target.name);
231
+ }
232
+ });
233
+ walk(ast, (node) => {
234
+ if (node.type !== "CallExpression") return;
235
+ const callee = node.callee;
236
+ let binding = null;
237
+ let name = "";
238
+ if (callee?.type === "MemberExpression" && callee.object?.type === "Identifier" && aliases.has(callee.object.name) && !shadowed.has(callee.object) && HOISTABLE.has(propertyName(callee.property) ?? "")) {
239
+ binding = aliases.get(callee.object.name);
240
+ name = `${callee.object.name}.${propertyName(callee.property)}`;
241
+ } else if (callee?.type === "Identifier" && methodAliases.has(callee.name) && !shadowed.has(callee)) {
242
+ binding = methodAliases.get(callee.name);
243
+ name = callee.name;
244
+ }
245
+ if (!binding) return;
246
+ const line = (at) => code.slice(0, at).split("\n").length;
247
+ throw new VitestNativeError("JEST_BINDING_NOT_FOLLOWED", `[vitest-native] jestMockTransform cannot follow \`${code.slice(binding.start, binding.end)}\` (${id.split("?")[0]}:${line(binding.start)}), so the \`${name}(…)\` call on line ${line(node.start)} would not be hoisted or registered. Jest does not hoist it either. Call it on the jest object itself: \`jest\`, or the name it is imported as from '@jest/globals'.`);
248
+ });
249
+ return { isJest };
250
+ }
37
251
  const FUNCTION = /* @__PURE__ */ new Set([
38
252
  "FunctionExpression",
39
253
  "ArrowFunctionExpression",
@@ -42,11 +256,11 @@ const FUNCTION = /* @__PURE__ */ new Set([
42
256
  const NODE_MODULES = /[\\/]node_modules[\\/]/;
43
257
  const SOURCE_FILE = /\.[cm]?[jt]sx?$/;
44
258
  /** The string specifier of a `jest.requireActual('<literal>')` call, or null. */
45
- function requireActualSpec(node) {
259
+ function requireActualSpec(node, jest) {
46
260
  if (node.type !== "CallExpression" || node.arguments.length !== 1) return null;
47
261
  const callee = node.callee;
48
262
  if (callee?.type !== "MemberExpression" || callee.computed) return null;
49
- if (callee.object?.type !== "Identifier" || callee.object.name !== "jest") return null;
263
+ if (!jest.isJest(callee.object)) return null;
50
264
  if (callee.property?.type !== "Identifier" || callee.property.name !== "requireActual") return null;
51
265
  return literalSpec(node.arguments[0]);
52
266
  }
@@ -68,11 +282,11 @@ const BINDS_REQUIRE = /\b(?:const|let|var|function|class)\s+require\b|\bimport\s
68
282
  * its own body, not in a nested function or a class body (where `await` is not allowed
69
283
  * either). `mocked` is the specifier the factory mocks, whose own require stays as is.
70
284
  */
71
- function ownLoadCalls(factory, mocked, requireIsGlobal) {
285
+ function ownLoadCalls(factory, mocked, requireIsGlobal, jest) {
72
286
  const calls = [];
73
287
  walk(factory.body, (node) => {
74
288
  if (FUNCTION.has(node.type) || node.type === "ClassBody") return false;
75
- const actual = requireActualSpec(node);
289
+ const actual = requireActualSpec(node, jest);
76
290
  if (actual !== null) return void calls.push({
77
291
  node,
78
292
  spec: actual,
@@ -146,7 +360,7 @@ function isViteOwnedSource(resolved, project) {
146
360
  * `jest.requireActual` loads, and `jest.requireMock` see the same mock the imports
147
361
  * do, as under Jest's single per-file module registry (see node-registry.mjs).
148
362
  *
149
- * Opt-in: add after `reactNative()`; pair with `jestCompatSetup` + `globals: true`.
363
+ * Opt-in: add after `reactNative()`; pair with `jestCompatSetup`.
150
364
  */
151
365
  function jestMockTransform(options = {}) {
152
366
  let project = {
@@ -175,14 +389,7 @@ function jestMockTransform(options = {}) {
175
389
  root,
176
390
  ...found
177
391
  });
178
- const setupFiles = Array.isArray(test.setupFiles) ? [...test.setupFiles] : test.setupFiles ? [test.setupFiles] : [];
179
- if (setupFiles.includes(id)) return;
180
- let compat = -1;
181
- setupFiles.forEach((file, index) => {
182
- if (JEST_COMPAT_SETUP.test(file)) compat = index;
183
- });
184
- setupFiles.splice(compat + 1, 0, id);
185
- test.setupFiles = setupFiles;
392
+ placeSetupFiles(test, [id], (file) => JEST_COMPAT_SETUP.test(file));
186
393
  },
187
394
  configResolved(config) {
188
395
  const native = config.plugins.find((plugin) => plugin.name === "vitest-native");
@@ -221,7 +428,7 @@ function jestMockTransform(options = {}) {
221
428
  if (id.includes("/node_modules/")) return null;
222
429
  const file = id.split("?")[0];
223
430
  if (!TRANSFORMABLE.test(file)) return null;
224
- if (!HAS_JEST_MOCK.test(code)) return null;
431
+ if (!HAS_JEST_MOCK.test(code) && !(NAMES_JEST.test(code) && NAMES_MOCK_METHOD.test(code))) return null;
225
432
  const owner = rootMockModules.has(file) ? projectsByRoot.get(rootMockModules.get(file).root) ?? project : project;
226
433
  let module;
227
434
  const spelled = path.isAbsolute(file) ? viteId(file) : file;
@@ -236,7 +443,8 @@ function jestMockTransform(options = {}) {
236
443
  };
237
444
  const finish = (adapted) => {
238
445
  if (!adapted?.changed) return null;
239
- if (adapted.usesSetup) adapted.s.prepend(SETUP_ACCESSOR);
446
+ if (adapted.usesSetup) adapted.s.prepend(setupAccessor(adapted.vi.name));
447
+ if (adapted.vi.add) adapted.s.append(`\nimport { ${adapted.vi.name} } from "vitest";\n`);
240
448
  return {
241
449
  code: adapted.s.toString(),
242
450
  map: adapted.s.generateMap({ hires: true })
@@ -374,15 +582,16 @@ function adapt(ctx, code, id, project, manualMockFor = () => null, automockable
374
582
  } catch {
375
583
  return null;
376
584
  }
585
+ const jest = jestBindings(ast, code, id);
377
586
  const candidates = /* @__PURE__ */ new Map();
378
587
  const requireIsGlobal = !BINDS_REQUIRE.test(code);
379
588
  walk(ast, (node) => {
380
- const factory = mockFactoryOf(node);
589
+ const factory = mockFactoryOf(node, jest);
381
590
  if (!factory || factory.generator) return;
382
- const calls = ownLoadCalls(factory, literalSpec(node.arguments[0]), requireIsGlobal);
591
+ const calls = ownLoadCalls(factory, literalSpec(node.arguments[0]), requireIsGlobal, jest);
383
592
  if (calls.length > 0) candidates.set(factory, calls);
384
593
  });
385
- if (candidates.size === 0) return rewrite(code, ast, /* @__PURE__ */ new Map(), manualMockFor, automockable);
594
+ if (candidates.size === 0) return rewrite(code, ast, jest, id, /* @__PURE__ */ new Map(), manualMockFor, automockable);
386
595
  const specs = new Set([...candidates.values()].flat().map((call) => call.spec));
387
596
  return Promise.all([...specs].map(async (spec) => {
388
597
  try {
@@ -397,15 +606,15 @@ function adapt(ctx, code, id, project, manualMockFor = () => null, automockable
397
606
  const moved = calls.filter((call) => owned.has(call.spec));
398
607
  if (moved.length > 0) toAsync.set(factory, moved);
399
608
  }
400
- return rewrite(code, ast, toAsync, manualMockFor, automockable);
609
+ return rewrite(code, ast, jest, id, toAsync, manualMockFor, automockable);
401
610
  });
402
611
  }
403
612
  /** The factory of a `jest.mock`/`jest.doMock` call with an inline function factory. */
404
- function mockFactoryOf(node) {
613
+ function mockFactoryOf(node, jest) {
405
614
  if (node.type !== "CallExpression" || node.arguments.length < 2) return null;
406
615
  const callee = node.callee;
407
616
  if (callee?.type !== "MemberExpression" || callee.computed) return null;
408
- if (callee.object?.type !== "Identifier" || callee.object.name !== "jest") return null;
617
+ if (!jest.isJest(callee.object)) return null;
409
618
  if (callee.property?.type !== "Identifier" || !WITH_FACTORY.has(callee.property.name)) return null;
410
619
  const factory = node.arguments[1];
411
620
  return factory.type === "ArrowFunctionExpression" || factory.type === "FunctionExpression" ? factory : null;
@@ -414,9 +623,20 @@ function mockFactoryOf(node) {
414
623
  * The transform itself. `toAsync` maps a factory to the `jest.requireActual` calls that
415
624
  * load through Vite instead (see "`jest.requireActual` of project source" above).
416
625
  */
417
- function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable = () => false) {
626
+ function rewrite(code, ast, jest, id, toAsync, manualMockFor = () => null, automockable = () => false) {
418
627
  const s = new MagicString(code);
419
628
  let changed = false;
629
+ let chosen;
630
+ const vi = () => {
631
+ if (chosen) return chosen.name;
632
+ const sites = new Set([...toAsync.values()].flat().map((call) => call.node));
633
+ walk(ast, (node) => {
634
+ if (node.type !== "CallExpression" || node.callee?.type !== "MemberExpression") return;
635
+ const { computed, object, property } = node.callee;
636
+ if (!computed && jest.isJest(object) && HOISTABLE.has(propertyName(property) ?? "")) sites.add(node);
637
+ });
638
+ return (chosen = vitestName(ast, id, sites)).name;
639
+ };
420
640
  const topLevel = /* @__PURE__ */ new Map();
421
641
  for (const statement of ast.body) if (statement.type === "ExpressionStatement") topLevel.set(statement.expression, statement);
422
642
  let usesSetup = false;
@@ -429,7 +649,7 @@ function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable =
429
649
  const arg = call.arguments[0];
430
650
  const spec = code.slice(arg.start, arg.end);
431
651
  text += code.slice(at, call.start);
432
- text += kind === "require" ? `(await ${SETUP}("__vnFactoryRequire")(import.meta.url, ${spec}, () => import(${spec})))` : `(${SETUP}("__vnActualExports")(await vi.importActual(${spec})))`;
652
+ text += kind === "require" ? `(await ${SETUP}("__vnFactoryRequire")(import.meta.url, ${spec}, () => import(${spec})))` : `(${SETUP}("__vnActualExports")(await ${vi()}.importActual(${spec})))`;
433
653
  at = call.end;
434
654
  }
435
655
  text += code.slice(at, factory.end);
@@ -442,9 +662,9 @@ function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable =
442
662
  if (!callee || callee.type !== "MemberExpression" || callee.computed) return;
443
663
  const obj = callee.object;
444
664
  const prop = callee.property;
445
- if (!obj || obj.type !== "Identifier" || obj.name !== "jest") return;
665
+ if (!jest.isJest(obj)) return;
446
666
  if (!prop || prop.type !== "Identifier" || !HOISTABLE.has(prop.name)) return;
447
- s.overwrite(obj.start, obj.end, "vi");
667
+ s.overwrite(obj.start, obj.end, vi());
448
668
  changed = true;
449
669
  if ((prop.name === "mock" || prop.name === "unmock") && !topLevel.has(node)) s.overwrite(prop.start, prop.end, prop.name === "mock" ? "doMock" : "doUnmock");
450
670
  const specNode = node.arguments[0];
@@ -455,18 +675,18 @@ function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable =
455
675
  if (manualMock !== null && mockStatement) {
456
676
  usesSetup = true;
457
677
  const name = jsString(literal);
458
- const register = `globalThis.__vnJestMock?.(import.meta.url, ${name}, ${manualMockFactory(manualMock)}, ${`async () => (${SETUP}("__vnActualExports")(await vi.importActual(${jsString(viteId(manualMock))})))`})`;
459
- s.prependLeft(mockStatement.start, `vi.hoisted(() => ${register});\n`);
678
+ const register = `globalThis.__vnJestMock?.(import.meta.url, ${name}, ${manualMockFactory(manualMock)}, ${`async () => (${SETUP}("__vnActualExports")(await ${vi()}.importActual(${jsString(viteId(manualMock))})))`})`;
679
+ s.prependLeft(mockStatement.start, `${vi()}.hoisted(() => ${register});\n`);
460
680
  s.appendLeft(specNode.end, `, () => ${SETUP}("__vnJestMocked")(import.meta.url, ${name})`);
461
681
  return;
462
682
  }
463
683
  if ((prop.name === "mock" || prop.name === "doMock") && node.arguments.length === 1 && literal !== null && automockable(literal)) {
464
684
  usesSetup = true;
465
685
  const name = jsString(literal);
466
- const register = `globalThis.__vnJestMock?.(import.meta.url, ${name}, ${`function __vnAutomock() { return vi.mockObject(jest.requireActual(${name})); }`})`;
686
+ const register = `globalThis.__vnJestMock?.(import.meta.url, ${name}, ${`function __vnAutomock() { return ${vi()}.mockObject(jest.requireActual(${name})); }`})`;
467
687
  const lookup = `() => ${SETUP}("__vnJestMocked")(import.meta.url, ${name})`;
468
688
  if (prop.name === "mock" && mockStatement) {
469
- s.prependLeft(mockStatement.start, `vi.hoisted(() => ${register});\n`);
689
+ s.prependLeft(mockStatement.start, `${vi()}.hoisted(() => ${register});\n`);
470
690
  s.appendLeft(specNode.end, `, ${lookup}`);
471
691
  } else s.appendLeft(specNode.end, `, (${register}, ${lookup})`);
472
692
  return;
@@ -482,7 +702,7 @@ function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable =
482
702
  const lookup = `() => ${SETUP}("__vnJestMocked")(import.meta.url, ${spec})`;
483
703
  const statement = topLevel.get(node);
484
704
  if (prop.name === "mock" && statement) {
485
- s.prependLeft(statement.start, `vi.hoisted(() => ${register});\n`);
705
+ s.prependLeft(statement.start, `${vi()}.hoisted(() => ${register});\n`);
486
706
  s.overwrite(factory.start, factory.end, lookup);
487
707
  } else s.overwrite(factory.start, factory.end, `(${register}, ${lookup})`);
488
708
  replaced.push([factory.start, factory.end]);
@@ -503,7 +723,11 @@ function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable =
503
723
  return {
504
724
  s,
505
725
  changed,
506
- usesSetup
726
+ usesSetup,
727
+ vi: chosen ?? {
728
+ name: "vi",
729
+ add: false
730
+ }
507
731
  };
508
732
  }
509
733
  // src/jest-compat/index.ts
@@ -26,6 +26,7 @@ import fs from "node:fs";
26
26
  import { createRequire } from "node:module";
27
27
  import path from "node:path";
28
28
  import { VitestNativeError } from "../errors.mjs";
29
+ import { listDirectory } from "./resolve.mjs";
29
30
  import { relativeToRoot } from "./root-spelling.mjs";
30
31
 
31
32
  // metro-config/src/defaults/defaults.js `assetExts` (0.87): the extensions Metro
@@ -146,19 +147,16 @@ export function parseAssetPath(filePath, platform) {
146
147
  }
147
148
 
148
149
  /**
149
- * metro/src/Assets.js `buildAssetMap` + `getAbsoluteAssetRecord`: every scale
150
- * variant of the asset in its directory, sorted by scale. A platform-specific
151
- * group (`icon.ios.png`, `icon@2x.ios.png`) wins over the generic one.
150
+ * metro/src/Assets.js `buildAssetMap`: every scale variant of every asset in `dir`,
151
+ * grouped by asset (and platform, for a variant of the platform being built) and
152
+ * sorted by scale.
152
153
  */
153
- function assetRecord(file, platform) {
154
- const dir = path.dirname(file);
155
- const key = (assetName, filePlatform) =>
156
- filePlatform != null ? `${assetName} : ${filePlatform}` : assetName;
154
+ function buildAssetGroups(dir, names, platform) {
157
155
  const groups = new Map();
158
- for (const entry of fs.readdirSync(dir)) {
156
+ for (const entry of names) {
159
157
  const asset = parseAssetPath(entry, platform);
160
158
  if (asset === null) continue;
161
- const groupKey = key(asset.assetName, asset.platform);
159
+ const groupKey = assetGroupKey(asset.assetName, asset.platform);
162
160
  let group = groups.get(groupKey);
163
161
  if (!group) groups.set(groupKey, (group = { scales: [], files: [] }));
164
162
  let at = 0;
@@ -166,9 +164,42 @@ function assetRecord(file, platform) {
166
164
  group.scales.splice(at, 0, asset.resolution);
167
165
  group.files.splice(at, 0, path.join(dir, entry));
168
166
  }
167
+ return groups;
168
+ }
169
+
170
+ const assetGroupKey = (assetName, filePlatform) =>
171
+ filePlatform != null ? `${assetName} : ${filePlatform}` : assetName;
172
+
173
+ // Folder listing → platform → its asset groups. The listing is the resolver's
174
+ // (resolve.mjs `listDirectory`), kept while the folder's stat is unchanged and replaced
175
+ // by a new map when it changes, so a folder of N icons is listed and parsed once per
176
+ // change rather than once per icon (#930). Groups are read, never mutated.
177
+ const groupsByListing = new WeakMap();
178
+
179
+ function assetGroups(dir, platform) {
180
+ const names = listDirectory(dir);
181
+ // Unreadable, missing or not a directory: read it here, which throws what reading it
182
+ // throws, as before the listing was shared.
183
+ if (names === null || names.size === 0) {
184
+ return buildAssetGroups(dir, fs.readdirSync(dir), platform);
185
+ }
186
+ let byPlatform = groupsByListing.get(names);
187
+ if (!byPlatform) groupsByListing.set(names, (byPlatform = new Map()));
188
+ let groups = byPlatform.get(platform);
189
+ if (!groups) byPlatform.set(platform, (groups = buildAssetGroups(dir, names.keys(), platform)));
190
+ return groups;
191
+ }
192
+
193
+ /**
194
+ * metro/src/Assets.js `getAbsoluteAssetRecord`: the requested asset's scale variants.
195
+ * A platform-specific group (`icon.ios.png`, `icon@2x.ios.png`) wins over the generic
196
+ * one.
197
+ */
198
+ function assetRecord(file, platform) {
199
+ const groups = assetGroups(path.dirname(file), platform);
169
200
  const requested = parseAssetPath(path.basename(file), platform);
170
201
  const record =
171
- (requested && groups.get(key(requested.assetName, platform))) ||
202
+ (requested && groups.get(assetGroupKey(requested.assetName, platform))) ||
172
203
  (requested && groups.get(requested.assetName));
173
204
  return record ? { requested, ...record } : null;
174
205
  }
@@ -12,12 +12,14 @@ import { workerData } from "node:worker_threads";
12
12
  const { port, signal, compileCache } = workerData;
13
13
 
14
14
  // Node's compile cache, on here exactly when it is on in the thread that started this
15
- // one (compile-cache.mjs decides), so Babel's modules load from it as they did there.
15
+ // one, so Babel's modules load from it as they did there. vitest-native never turns it
16
+ // on (#831); a NODE_COMPILE_CACHE the developer sets does, in every thread, and every
17
+ // test worker then writes its entries when it exits, inside the pool's close.
16
18
  if (compileCache) {
17
19
  try {
18
20
  (await import("node:module")).default.enableCompileCache?.(compileCache);
19
21
  } catch {
20
- // A pure optimization, as in compile-cache.mjs.
22
+ // A pure optimization.
21
23
  }
22
24
  }
23
25
 
@@ -98,14 +98,20 @@ const MOCK_NATIVE_COMPONENT = `
98
98
  ]);
99
99
  const mockNativeComponent = (viewName) => {
100
100
  const hostName = __TEXT_INPUT_VIEWS.has(viewName) ? "TextInput" : viewName;
101
- // The native methods a ref has, on a plain object the class delegates to: a spy that
102
- // replaces one there reaches every ref of this view. jest-compat gives it to View,
103
- // Text and ScrollView as their prototype, as React Native's Jest preset has one. It
104
- // is not the class's own prototype, which would make React construct those function
105
- // components as classes.
106
- const nativeMethods = {
101
+ // The native methods a ref has, on an object between the class's prototype and
102
+ // React.Component's, so a ref inherits them and anything else put there: jest-compat
103
+ // gives it to View as its prototype, as React Native's Jest preset has one, and suites
104
+ // spy on methods there or add their own (react-native-paper's Menu tests add
105
+ // querySelector). A spy that replaces one reaches every ref of this view. The object
106
+ // shadows isReactComponent with undefined, so a component given it as its prototype is
107
+ // not taken for a class (by React, or by a library's createAnimatedComponent); the
108
+ // class keeps its own.
109
+ const nativeMethods = Object.create(React.Component.prototype, {
110
+ isReactComponent: { value: undefined, writable: true, configurable: true },
111
+ });
112
+ Object.assign(nativeMethods, {
107
113
  blur() {}, focus() {}, measure() {}, measureInWindow() {}, measureLayout() {}, setNativeProps() {},
108
- };
114
+ });
109
115
  const C = class extends React.Component {
110
116
  constructor(p) { super(p); this._nativeTag = __tag++; }
111
117
  render() {
@@ -116,13 +122,11 @@ const MOCK_NATIVE_COMPONENT = `
116
122
  }
117
123
  return React.createElement(hostName, props, props.children);
118
124
  }
119
- blur(...a) { return nativeMethods.blur.apply(this, a); }
120
- focus(...a) { return nativeMethods.focus.apply(this, a); }
121
- measure(...a) { return nativeMethods.measure.apply(this, a); }
122
- measureInWindow(...a) { return nativeMethods.measureInWindow.apply(this, a); }
123
- measureLayout(...a) { return nativeMethods.measureLayout.apply(this, a); }
124
- setNativeProps(...a) { return nativeMethods.setNativeProps.apply(this, a); }
125
125
  };
126
+ Object.setPrototypeOf(C.prototype, nativeMethods);
127
+ Object.defineProperty(C.prototype, "isReactComponent", {
128
+ value: React.Component.prototype.isReactComponent, writable: true, configurable: true,
129
+ });
126
130
  C.displayName = viewName === "RCTView" ? "View" : hostName;
127
131
  C.nativeMethods = nativeMethods;
128
132
  return C;
@@ -447,11 +451,42 @@ const EXPO_DEV_STUBS = {
447
451
  };
448
452
  const EXPO_SUFFIXES = Object.keys(EXPO_DEV_STUBS);
449
453
 
454
+ /**
455
+ * expo-modules-core's `createSnapshotFriendlyRef` (src/Refs.ts) is React's `createRef`.
456
+ * Expo modules pass refs made with it to their native views as props: expo-image's
457
+ * `nativeViewRef` and `containerViewRef`. A snapshot then printed the host instance and
458
+ * React's fiber tree behind them, thousands of lines with render timings that differ on
459
+ * every run. jest-expo serves a ref that prints as "[React.ref]" (src/preset/setup.js),
460
+ * and this is that ref: `{ current: null }` with a non-enumerable `toJSON`.
461
+ */
462
+ const SNAPSHOT_FRIENDLY_REF = `
463
+ exports.createSnapshotFriendlyRef = function createSnapshotFriendlyRef() {
464
+ const ref = { current: null };
465
+ Object.defineProperty(ref, "toJSON", { value: () => "[React.ref]" });
466
+ return ref;
467
+ };
468
+ `;
469
+ const EXPO_MODULES_CORE_STUBS = {
470
+ "build/Refs.js": SNAPSHOT_FRIENDLY_REF,
471
+ "src/Refs.ts": SNAPSHOT_FRIENDLY_REF,
472
+ };
473
+ const EXPO_MODULES_CORE_SUFFIXES = Object.keys(EXPO_MODULES_CORE_STUBS);
474
+
475
+ /**
476
+ * The stand-ins for files outside react-native, by package directory. The registry keys
477
+ * on them, so a changed stand-in is not served from a registry built with the old one.
478
+ */
479
+ export const PACKAGE_STUBS = {
480
+ expo: EXPO_DEV_STUBS,
481
+ "expo-modules-core": EXPO_MODULES_CORE_STUBS,
482
+ };
483
+
450
484
  /** Normalised-path test: is this a native-boundary module? */
451
485
  export function isBoundary(normPath) {
452
486
  return (
453
487
  SUFFIXES.some((s) => normPath.endsWith("/react-native/" + s)) ||
454
- EXPO_SUFFIXES.some((s) => normPath.endsWith("/expo/" + s))
488
+ EXPO_SUFFIXES.some((s) => normPath.endsWith("/expo/" + s)) ||
489
+ EXPO_MODULES_CORE_SUFFIXES.some((s) => normPath.endsWith("/expo-modules-core/" + s))
455
490
  );
456
491
  }
457
492
 
@@ -466,5 +501,8 @@ export function boundarySourceFor(normPath, platform = "ios", version = "0.0.0")
466
501
  for (const s of EXPO_SUFFIXES) {
467
502
  if (normPath.endsWith("/expo/" + s)) return EXPO_DEV_STUBS[s];
468
503
  }
504
+ for (const s of EXPO_MODULES_CORE_SUFFIXES) {
505
+ if (normPath.endsWith("/expo-modules-core/" + s)) return EXPO_MODULES_CORE_STUBS[s];
506
+ }
469
507
  return null;
470
508
  }