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.
- package/CHANGELOG.md +1063 -0
- package/README.md +47 -2
- package/dist/cli.cjs +642 -0
- package/dist/cli.d.cts +4 -0
- package/dist/cli.d.mts +4 -0
- package/dist/cli.mjs +638 -0
- package/dist/ecosystem-CO5vqExO.mjs +318 -0
- package/dist/ecosystem-IuZ-Gv0R.cjs +356 -0
- package/dist/errors-Dm5yLNTF.mjs +64 -0
- package/dist/errors-flXDIeWk.cjs +75 -0
- package/dist/errors.d.mts +46 -0
- package/dist/errors.mjs +78 -0
- package/dist/helpers.cjs +6 -23
- package/dist/helpers.d.cts +0 -6
- package/dist/helpers.d.mts +0 -6
- package/dist/helpers.mjs +6 -23
- package/dist/{index-vlK4zxuK.d.mts → index-BJL4cQ-l.d.cts} +22 -7
- package/dist/{index-YjjYELG7.d.cts → index-CvCU0cLl.d.mts} +20 -9
- package/dist/index.d.mts +8 -6
- package/dist/index.mjs +563 -232
- package/dist/jest-compat/interop.mjs +15 -0
- package/dist/jest-compat/setup.mjs +164 -5
- package/dist/matchers.cjs +16 -7
- package/dist/matchers.mjs +16 -7
- package/dist/native/boundary.mjs +108 -30
- package/dist/native/compile-cache.mjs +10 -5
- package/dist/native/explain.mjs +69 -0
- package/dist/native/hooks.mjs +151 -4
- package/dist/native/loader.mjs +61 -12
- package/dist/native/match.mjs +107 -8
- package/dist/native/module-reset.mjs +63 -0
- package/dist/native/registry.mjs +540 -0
- package/dist/native/reset.mjs +18 -12
- package/dist/native/resolve.d.mts +22 -0
- package/dist/native/resolve.mjs +21 -13
- package/dist/native/runner.mjs +34 -7
- package/dist/native/setup.mjs +19 -3
- package/dist/native/transform.mjs +195 -21
- package/dist/native/worker.mjs +69 -17
- package/dist/pool-Bcxp4Qrg.mjs +118 -0
- package/dist/pool-CFND7plG.cjs +122 -0
- package/dist/{preset-map-DCWaM08s.mjs → preset-map-BpDG_D5m.mjs} +1 -1
- package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-DxilQ4pI.cjs} +1 -1
- package/dist/{presets-7eMfp7o2.cjs → presets-BGTqVH6C.cjs} +227 -52
- package/dist/{presets-23FJ76O4.mjs → presets-CK85x8ey.mjs} +222 -53
- package/dist/presets.d.mts +2 -2
- package/dist/presets.mjs +2 -2
- package/dist/rntl-matchers.d.ts +35 -0
- package/dist/serializer.cjs +33 -3
- package/dist/serializer.mjs +33 -3
- package/dist/setup.mjs +544 -193
- package/docs/hot-default-design.md +129 -0
- package/docs/migrating-from-jest.md +43 -7
- package/docs/migrating-from-vitest-react-native.md +1 -1
- package/docs/release-readiness.md +24 -6
- package/docs/versioning.md +133 -0
- package/package.json +40 -38
- package/dist/index.cjs +0 -643
- package/dist/index.d.cts +0 -14
- package/dist/pool-B7LBfcMQ.mjs +0 -67
- package/dist/pool-p54QV1dQ.cjs +0 -69
- package/dist/presets.cjs +0 -17
- package/dist/presets.d.cts +0 -2
- package/dist/setup.cjs +0 -2514
- package/dist/setup.d.cts +0 -1
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const require_chunk = require("./chunk-CZWwpsFl.cjs");
|
|
4
|
+
const require_ecosystem = require("./ecosystem-IuZ-Gv0R.cjs");
|
|
5
|
+
const require_preset_map = require("./preset-map-DxilQ4pI.cjs");
|
|
6
|
+
let node_fs = require("node:fs");
|
|
7
|
+
node_fs = require_chunk.__toESM(node_fs, 1);
|
|
8
|
+
let node_path = require("node:path");
|
|
9
|
+
node_path = require_chunk.__toESM(node_path, 1);
|
|
10
|
+
let node_module = require("node:module");
|
|
11
|
+
//#region src/cli/doctor.ts
|
|
12
|
+
/**
|
|
13
|
+
* `vitest-native doctor` — diagnose the project's environment: peer versions,
|
|
14
|
+
* engine resolution (and why), detected presets, RNTL/Node compatibility, and
|
|
15
|
+
* config presence. Read-only; never mutates the project.
|
|
16
|
+
*/
|
|
17
|
+
function packageVersion(root, name) {
|
|
18
|
+
try {
|
|
19
|
+
return (0, node_module.createRequire)(node_path.default.join(root, "package.json"))(`${name}/package.json`).version ?? null;
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
|
|
26
|
+
* is used when there is none.
|
|
27
|
+
*
|
|
28
|
+
* The vite.config entries were missing, so a correct setup that configures Vitest
|
|
29
|
+
* from vite.config.ts — normal in projects that already had Vite — was told "no
|
|
30
|
+
* vitest.config.* found — run `vitest-native init`". Following that produces a
|
|
31
|
+
* second config which then TAKES PRECEDENCE over the working one, so the advice
|
|
32
|
+
* did not just misreport, it would have broken the project.
|
|
33
|
+
*/
|
|
34
|
+
const CONFIG_FILES = [
|
|
35
|
+
"vitest.config.ts",
|
|
36
|
+
"vitest.config.mts",
|
|
37
|
+
"vitest.config.js",
|
|
38
|
+
"vitest.config.mjs",
|
|
39
|
+
"vitest.config.cts",
|
|
40
|
+
"vitest.config.cjs",
|
|
41
|
+
"vite.config.ts",
|
|
42
|
+
"vite.config.mts",
|
|
43
|
+
"vite.config.js",
|
|
44
|
+
"vite.config.mjs",
|
|
45
|
+
"vite.config.cts",
|
|
46
|
+
"vite.config.cjs"
|
|
47
|
+
];
|
|
48
|
+
function findConfigFile(root) {
|
|
49
|
+
for (const name of CONFIG_FILES) if (node_fs.default.existsSync(node_path.default.join(root, name))) return name;
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
/** Source with comments removed, so a mention inside one cannot be mistaken for use. */
|
|
53
|
+
function withoutComments(source) {
|
|
54
|
+
return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Whether a config is built on one imported from elsewhere — a shared preset in a
|
|
58
|
+
* workspace, typically. Such a file legitimately never mentions vitest-native, and
|
|
59
|
+
* reporting it as unconfigured is a false alarm on a working project.
|
|
60
|
+
*/
|
|
61
|
+
function extendsSharedConfig(source) {
|
|
62
|
+
const code = withoutComments(source);
|
|
63
|
+
const imports = [...code.matchAll(/import\s+([^;]+?)\s+from\s*["']([^"'.][^"']*)["']/g)];
|
|
64
|
+
for (const [, clause, specifier] of imports) {
|
|
65
|
+
if (specifier === "vitest" || specifier.startsWith("vitest/")) continue;
|
|
66
|
+
const bindings = [...clause.matchAll(/([A-Za-z_$][\w$]*)/g)].map((m) => m[1]);
|
|
67
|
+
for (const binding of bindings) {
|
|
68
|
+
if (binding === "defineConfig" || binding === "default") continue;
|
|
69
|
+
if (new RegExp(`export\\s+default\\s+${binding}\\s*;?\\s*$`, "m").test(code)) return true;
|
|
70
|
+
if (new RegExp(`\\bmergeConfig\\s*\\(\\s*${binding}\\b`).test(code)) return true;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Whether a config genuinely uses the plugin.
|
|
77
|
+
*
|
|
78
|
+
* This was a substring test — `content.includes("vitest-native")` — so a config
|
|
79
|
+
* whose only mention was a `// TODO: migrate to vitest-native` comment reported
|
|
80
|
+
* "uses vitest-native" and "No blocking problems found", on a project where every
|
|
81
|
+
* React Native import would fail. Diagnosing that is the entire job of this
|
|
82
|
+
* command.
|
|
83
|
+
*
|
|
84
|
+
* The binding name is read from the import rather than assumed, so an aliased
|
|
85
|
+
* import still counts as used; when the import shape is not one of the forms
|
|
86
|
+
* below, the import alone is accepted rather than risking a false alarm on a
|
|
87
|
+
* working project.
|
|
88
|
+
*/
|
|
89
|
+
function analyzeConfigUsage(source) {
|
|
90
|
+
const code = withoutComments(source);
|
|
91
|
+
const named = /import\s*\{([^}]*)\}\s*from\s*["']vitest-native["']/.exec(code);
|
|
92
|
+
const namespaced = /import\s*\*\s*as\s*([A-Za-z_$][\w$]*)\s*from\s*["']vitest-native["']/.exec(code);
|
|
93
|
+
const required = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*["']vitest-native["']\s*\)/.exec(code);
|
|
94
|
+
const bindingFrom = (clause) => {
|
|
95
|
+
const entry = /\breactNative\b(?:\s*(?::|as)\s*([A-Za-z_$][\w$]*))?/.exec(clause);
|
|
96
|
+
return entry ? entry[1] ?? "reactNative" : null;
|
|
97
|
+
};
|
|
98
|
+
if (named || required) {
|
|
99
|
+
const binding = bindingFrom((named ?? required)[1]);
|
|
100
|
+
if (!binding) return {
|
|
101
|
+
imports: true,
|
|
102
|
+
invokes: true
|
|
103
|
+
};
|
|
104
|
+
return {
|
|
105
|
+
imports: true,
|
|
106
|
+
invokes: new RegExp(`\\b${binding}\\s*\\(`).test(code)
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
if (namespaced) return {
|
|
110
|
+
imports: true,
|
|
111
|
+
invokes: new RegExp(`\\b${namespaced[1]}\\.\\w+\\s*\\(`).test(code)
|
|
112
|
+
};
|
|
113
|
+
if (/from\s*["']vitest-native["']|require\(\s*["']vitest-native["']\s*\)/.test(code)) return {
|
|
114
|
+
imports: true,
|
|
115
|
+
invokes: true
|
|
116
|
+
};
|
|
117
|
+
return {
|
|
118
|
+
imports: false,
|
|
119
|
+
invokes: false
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The directory a test run would actually resolve from.
|
|
124
|
+
*
|
|
125
|
+
* `doctor` resolved peers from its own working directory. In a workspace that is
|
|
126
|
+
* frequently not where the Vitest config lives, and under pnpm a package's
|
|
127
|
+
* node_modules holds only its DECLARED dependencies — so a hoisted
|
|
128
|
+
* `@react-native/babel-preset` does not resolve from the package even though the
|
|
129
|
+
* real run finds it. The result was `doctor` reporting "engine 'auto' resolves to
|
|
130
|
+
* MOCK" for a project whose run banner said native.
|
|
131
|
+
*
|
|
132
|
+
* This is a FALLBACK, not a replacement. Node resolution walks upward, so the
|
|
133
|
+
* directory the command was invoked in already sees its own dependencies AND
|
|
134
|
+
* everything declared above it — resolving from higher up can only see less. Using
|
|
135
|
+
* the config root unconditionally lost dependencies a package declared itself, and
|
|
136
|
+
* reported a missing peer for a project that had one: the inverse of the bug this
|
|
137
|
+
* was written for.
|
|
138
|
+
*
|
|
139
|
+
* So the invocation directory is tried first, and this is consulted only when
|
|
140
|
+
* something fails to resolve there — which is the case where the command was run
|
|
141
|
+
* above the package that declares it.
|
|
142
|
+
*/
|
|
143
|
+
function resolutionRoot(start, exists = node_fs.default.existsSync) {
|
|
144
|
+
let dir = start;
|
|
145
|
+
for (;;) {
|
|
146
|
+
if (CONFIG_FILES.some((name) => exists(node_path.default.join(dir, name))) && exists(node_path.default.join(dir, "package.json"))) return dir;
|
|
147
|
+
if (exists(node_path.default.join(dir, ".git"))) return start;
|
|
148
|
+
const parent = node_path.default.dirname(dir);
|
|
149
|
+
if (parent === dir) return start;
|
|
150
|
+
dir = parent;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function runDoctor(root, nodeVersion = process.versions.node) {
|
|
154
|
+
const lines = [];
|
|
155
|
+
let ok = true;
|
|
156
|
+
const pass = (s) => lines.push(` ✓ ${s}`);
|
|
157
|
+
const warn = (s) => lines.push(` ⚠ ${s}`);
|
|
158
|
+
const fail = (s) => {
|
|
159
|
+
ok = false;
|
|
160
|
+
lines.push(` ✗ ${s}`);
|
|
161
|
+
};
|
|
162
|
+
const configRoot = resolutionRoot(root);
|
|
163
|
+
const resolvesHere = (name) => packageVersion(root, name) !== null;
|
|
164
|
+
const rootFor = (name) => resolvesHere(name) || configRoot === root ? root : configRoot;
|
|
165
|
+
lines.push(`vitest-native doctor — ${root}`);
|
|
166
|
+
lines.push("", "Runtime");
|
|
167
|
+
const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
|
|
168
|
+
if (nodeMajorMinor[0] >= 20) pass(`Node ${nodeVersion} (floor: 20)`);
|
|
169
|
+
else fail(`Node ${nodeVersion} — vitest-native requires Node >= 20.`);
|
|
170
|
+
lines.push("", "Peer dependencies");
|
|
171
|
+
for (const { name, minimum, maximumMajor, minimumByMajor, optional } of require_ecosystem.PEER_REQUIREMENTS) {
|
|
172
|
+
if (optional) continue;
|
|
173
|
+
const from = rootFor(name);
|
|
174
|
+
const error = require_ecosystem.validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor);
|
|
175
|
+
if (error) fail(error);
|
|
176
|
+
else {
|
|
177
|
+
pass(`${name} ${packageVersion(from, name)}`);
|
|
178
|
+
if (from !== root) lines.push(` (resolved from ${from}, not from here)`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
lines.push("", "Engine");
|
|
182
|
+
const rnVersion = packageVersion(rootFor("react-native"), "react-native");
|
|
183
|
+
if (require_ecosystem.detectEngine("auto", rootFor("@react-native/babel-preset")).engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with @react-native/babel-preset + @babel/core present.`);
|
|
184
|
+
else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but @react-native/babel-preset and/or @babel/core do not resolve. Install both as devDependencies to run the real-RN native engine.`);
|
|
185
|
+
else warn("engine 'auto' resolves to MOCK: react-native is not installed. That is fine for pure-logic suites; install react-native (+ its babel preset) for the native engine.");
|
|
186
|
+
lines.push("", "Testing library");
|
|
187
|
+
const rntl = packageVersion(rootFor("@testing-library/react-native"), "@testing-library/react-native");
|
|
188
|
+
if (!rntl) warn("@testing-library/react-native not found — optional, but required for render()/screen queries.");
|
|
189
|
+
else {
|
|
190
|
+
const rntlMajor = Number(rntl.split(".")[0]);
|
|
191
|
+
const rntlReq = require_ecosystem.PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
|
|
192
|
+
const rntlError = rntlReq && require_ecosystem.validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
|
|
193
|
+
if (rntlError) warn(rntlError);
|
|
194
|
+
else if (rntlMajor >= 14 && (nodeMajorMinor[0] < 22 || nodeMajorMinor[0] === 22 && nodeMajorMinor[1] < 13)) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
|
|
195
|
+
else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
|
|
196
|
+
}
|
|
197
|
+
lines.push("", "Auto-detected presets");
|
|
198
|
+
const req = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
|
|
199
|
+
const detected = [];
|
|
200
|
+
for (const [pkg, preset] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) try {
|
|
201
|
+
req.resolve(pkg);
|
|
202
|
+
detected.push(`${pkg} → ${preset}`);
|
|
203
|
+
} catch {}
|
|
204
|
+
if (detected.length) for (const d of detected) pass(d);
|
|
205
|
+
else lines.push(" (none — no preset-covered packages installed)");
|
|
206
|
+
const expo = packageVersion(rootFor("expo"), "expo");
|
|
207
|
+
if (expo) {
|
|
208
|
+
lines.push("", "Expo");
|
|
209
|
+
warn(`expo ${expo} detected. Expo-module components work via the auto-detected preset; suites that import Expo CORE internals (expo-router setups, dev-client wiring) can hit known limits — see the Jest migration guide's Expo notes.`);
|
|
210
|
+
}
|
|
211
|
+
lines.push("", "Config");
|
|
212
|
+
const configFile = findConfigFile(configRoot);
|
|
213
|
+
if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
|
|
214
|
+
else {
|
|
215
|
+
const content = node_fs.default.readFileSync(node_path.default.join(configRoot, configFile), "utf8");
|
|
216
|
+
const usage = analyzeConfigUsage(content);
|
|
217
|
+
if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
|
|
218
|
+
else if (usage.imports) warn(`${configFile} imports vitest-native but never calls reactNative() — the plugin is not in \`plugins: [...]\`, so React Native imports will not resolve.`);
|
|
219
|
+
else if (extendsSharedConfig(content)) lines.push(` · ${configFile} builds on a shared config, so this cannot tell from here whether the plugin is wired up. Check the config it extends.`);
|
|
220
|
+
else warn(`${configFile} exists but does not import vitest-native` + (content.includes("vitest-native") ? " (it is only mentioned in a comment)" : "") + " — add `reactNative()` to `plugins: [...]`, or run `vitest-native init`.");
|
|
221
|
+
}
|
|
222
|
+
lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
|
|
223
|
+
return {
|
|
224
|
+
lines,
|
|
225
|
+
ok
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
//#endregion
|
|
229
|
+
//#region src/cli/init.ts
|
|
230
|
+
/**
|
|
231
|
+
* `vitest-native init` — write a ready-to-run Vitest config. Two shapes:
|
|
232
|
+
* the zero-config default, and the jest-compat variant (the exact block the
|
|
233
|
+
* migration guide documents, so docs and CLI can never drift apart by shape).
|
|
234
|
+
*/
|
|
235
|
+
const PLAIN_CONFIG = `import { defineConfig } from 'vitest/config'
|
|
236
|
+
import { reactNative } from 'vitest-native'
|
|
237
|
+
|
|
238
|
+
export default defineConfig({
|
|
239
|
+
// Zero config: engine 'auto' runs REAL React Native (mocking only the native
|
|
240
|
+
// boundary) when @react-native/babel-preset + @babel/core are present, and
|
|
241
|
+
// falls back to the pure-JS mock engine otherwise.
|
|
242
|
+
plugins: [reactNative()],
|
|
243
|
+
test: {
|
|
244
|
+
environment: 'node',
|
|
245
|
+
},
|
|
246
|
+
})
|
|
247
|
+
`;
|
|
248
|
+
const JEST_COMPAT_CONFIG = `import { defineConfig } from 'vitest/config'
|
|
249
|
+
import { reactNative } from 'vitest-native'
|
|
250
|
+
import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
|
|
251
|
+
|
|
252
|
+
export default defineConfig({
|
|
253
|
+
// jestMockTransform() rewrites top-level jest.mock(...) into hoisted vi.mock(...).
|
|
254
|
+
// Leave it without an \`enforce\`: it has to run after Vite strips TS/JSX and before
|
|
255
|
+
// Vitest's own mock hoister. Its position relative to reactNative() does not matter.
|
|
256
|
+
plugins: [reactNative(), jestMockTransform()],
|
|
257
|
+
resolve: {
|
|
258
|
+
dedupe: ['react', 'react-test-renderer', 'react-is'],
|
|
259
|
+
alias: { ...jestCompatAliases() },
|
|
260
|
+
},
|
|
261
|
+
test: {
|
|
262
|
+
globals: true,
|
|
263
|
+
environment: 'node',
|
|
264
|
+
setupFiles: [jestCompatSetup],
|
|
265
|
+
},
|
|
266
|
+
})
|
|
267
|
+
`;
|
|
268
|
+
function renderInitConfig(jestCompat) {
|
|
269
|
+
return jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
|
|
270
|
+
}
|
|
271
|
+
function existingConfig(root) {
|
|
272
|
+
for (const name of [
|
|
273
|
+
"vitest.config.ts",
|
|
274
|
+
"vitest.config.mts",
|
|
275
|
+
"vitest.config.js",
|
|
276
|
+
"vitest.config.mjs",
|
|
277
|
+
"vitest.config.cts",
|
|
278
|
+
"vitest.config.cjs"
|
|
279
|
+
]) if (node_fs.default.existsSync(node_path.default.join(root, name))) return name;
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
function runInit(root, opts = {}) {
|
|
283
|
+
const lines = [];
|
|
284
|
+
const existing = existingConfig(root);
|
|
285
|
+
if (existing && !opts.force) return {
|
|
286
|
+
lines: [`✗ ${existing} already exists — not overwriting. Re-run with --force to replace it,`, ` or run \`vitest-native migrate\` to analyze an existing Jest setup first.`],
|
|
287
|
+
ok: false
|
|
288
|
+
};
|
|
289
|
+
const file = node_fs.default.existsSync(node_path.default.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
|
|
290
|
+
const target = node_path.default.join(root, file);
|
|
291
|
+
node_fs.default.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false));
|
|
292
|
+
lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`);
|
|
293
|
+
if (existing && opts.force) lines.push(` (replaced ${existing === file ? "it" : existing})`);
|
|
294
|
+
lines.push("", "Next steps:", ` 1. add a script: "test": "vitest"`, ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
|
|
295
|
+
if (opts.jestCompat) lines.push(` 4. migrating a Jest suite? \`vitest-native migrate\` maps your jest.config onto this file.`);
|
|
296
|
+
return {
|
|
297
|
+
lines,
|
|
298
|
+
ok: true,
|
|
299
|
+
wrote: file
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
//#endregion
|
|
303
|
+
//#region src/cli/migrate.ts
|
|
304
|
+
/**
|
|
305
|
+
* `vitest-native migrate` — analyze a project's Jest configuration and report,
|
|
306
|
+
* key by key, what maps automatically, what the presets already cover (delete
|
|
307
|
+
* it), and what needs a human. Dry-run by default; --write emits the suggested
|
|
308
|
+
* Vitest config. It never edits test files: `jestMockTransform()` handles
|
|
309
|
+
* top-level `jest.mock` at runtime, so file codemods aren't required to start.
|
|
310
|
+
*/
|
|
311
|
+
/**
|
|
312
|
+
* Extract package names from Jest's classic transformIgnorePatterns allowlist
|
|
313
|
+
* (`node_modules/(?!(?:pkg1|@scope/pkg2|...)/)`). Best-effort by design: the
|
|
314
|
+
* raw pattern is always surfaced in the report alongside the extraction, and
|
|
315
|
+
* entries the extraction cannot be confident about (capturing groups like
|
|
316
|
+
* `(jest-)?react-native`, whose strip would fabricate a package name) are
|
|
317
|
+
* returned separately instead of guessed at.
|
|
318
|
+
*/
|
|
319
|
+
function extractAllowlistPackages(pattern) {
|
|
320
|
+
const m = /\(\?!((?:[^()]|\([^()]*\))*)\)/.exec(pattern);
|
|
321
|
+
if (!m) return {
|
|
322
|
+
packages: [],
|
|
323
|
+
unparseable: []
|
|
324
|
+
};
|
|
325
|
+
const packages = [];
|
|
326
|
+
const unparseable = [];
|
|
327
|
+
for (const raw of m[1].split("|")) {
|
|
328
|
+
const entry = raw.trim();
|
|
329
|
+
if (!entry) continue;
|
|
330
|
+
if (/\((?!\?)/.test(entry)) {
|
|
331
|
+
unparseable.push(entry);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
const cleaned = entry.replace(/\(\?:/g, "").replace(/[()?*^$]/g, "").replace(/\\\//g, "/").replace(/\/\.$/, "").replace(/\/$/, "").replace(/\.$/, "").trim();
|
|
335
|
+
if (cleaned.length > 0 && !cleaned.includes("\\")) packages.push(cleaned);
|
|
336
|
+
else if (entry.length > 0) unparseable.push(entry);
|
|
337
|
+
}
|
|
338
|
+
return {
|
|
339
|
+
packages,
|
|
340
|
+
unparseable
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
function loadJestConfig(root) {
|
|
344
|
+
const req = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
|
|
345
|
+
for (const name of [
|
|
346
|
+
"jest.config.js",
|
|
347
|
+
"jest.config.cjs",
|
|
348
|
+
"jest.config.json"
|
|
349
|
+
]) {
|
|
350
|
+
const file = node_path.default.join(root, name);
|
|
351
|
+
if (!node_fs.default.existsSync(file)) continue;
|
|
352
|
+
try {
|
|
353
|
+
const loaded = name.endsWith(".json") ? JSON.parse(node_fs.default.readFileSync(file, "utf8")) : req(file);
|
|
354
|
+
const config = loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
|
|
355
|
+
if (typeof config === "function") return {
|
|
356
|
+
source: name,
|
|
357
|
+
config: null
|
|
358
|
+
};
|
|
359
|
+
return {
|
|
360
|
+
source: name,
|
|
361
|
+
config
|
|
362
|
+
};
|
|
363
|
+
} catch {
|
|
364
|
+
return {
|
|
365
|
+
source: name,
|
|
366
|
+
config: null
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
for (const name of [
|
|
371
|
+
"jest.config.mjs",
|
|
372
|
+
"jest.config.ts",
|
|
373
|
+
"jest.config.mts"
|
|
374
|
+
]) if (node_fs.default.existsSync(node_path.default.join(root, name))) return {
|
|
375
|
+
source: name,
|
|
376
|
+
config: null
|
|
377
|
+
};
|
|
378
|
+
try {
|
|
379
|
+
const pkg = JSON.parse(node_fs.default.readFileSync(node_path.default.join(root, "package.json"), "utf8"));
|
|
380
|
+
if (pkg.jest && typeof pkg.jest === "object") return {
|
|
381
|
+
source: "package.json#jest",
|
|
382
|
+
config: pkg.jest
|
|
383
|
+
};
|
|
384
|
+
} catch {}
|
|
385
|
+
return {
|
|
386
|
+
source: null,
|
|
387
|
+
config: null
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
function analyzeJestConfig(root) {
|
|
391
|
+
const { source, config } = loadJestConfig(root);
|
|
392
|
+
const automatic = [];
|
|
393
|
+
const attention = [];
|
|
394
|
+
const presetCovered = [];
|
|
395
|
+
const dropped = [];
|
|
396
|
+
const testEntries = [`globals: true`, `environment: 'node'`];
|
|
397
|
+
const setupFiles = ["jestCompatSetup"];
|
|
398
|
+
const aliasEntries = ["...jestCompatAliases()"];
|
|
399
|
+
const transformPkgs = [];
|
|
400
|
+
const autoInlined = new Set(require_ecosystem.detectEcosystemPackages(root));
|
|
401
|
+
let needsUrlImport = false;
|
|
402
|
+
const presetPkgs = new Set(Object.keys(require_preset_map.AUTO_DETECT_PRESETS));
|
|
403
|
+
if (config) {
|
|
404
|
+
const handled = /* @__PURE__ */ new Set();
|
|
405
|
+
const take = (key) => {
|
|
406
|
+
handled.add(key);
|
|
407
|
+
return config[key];
|
|
408
|
+
};
|
|
409
|
+
const preset = take("preset");
|
|
410
|
+
if (preset === "react-native" || preset === "@react-native/jest-preset") automatic.push(`preset: '${preset}' → replaced by the reactNative() plugin.`);
|
|
411
|
+
else if (preset === "jest-expo") attention.push("preset: 'jest-expo' → the reactNative() plugin + auto-detected expo preset replace most of it, but suites importing Expo CORE internals can hit known limits (see the migration guide's Expo notes).");
|
|
412
|
+
else if (preset) attention.push(`preset: '${preset}' — unknown preset; review what it configured.`);
|
|
413
|
+
for (const key of ["setupFiles", "setupFilesAfterEnv"]) {
|
|
414
|
+
const files = take(key);
|
|
415
|
+
if (!files?.length) continue;
|
|
416
|
+
for (const f of files) if (/react-native\/jest\/setup|jest-expo/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
|
|
417
|
+
else if (f.startsWith("<rootDir>")) {
|
|
418
|
+
setupFiles.push(`fileURLToPath(new URL(${JSON.stringify(f.replace(/^<rootDir>\/?/, "./"))}, import.meta.url))`);
|
|
419
|
+
needsUrlImport = true;
|
|
420
|
+
automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
|
|
421
|
+
} else {
|
|
422
|
+
setupFiles.push(JSON.stringify(f));
|
|
423
|
+
automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
const mapper = take("moduleNameMapper");
|
|
427
|
+
if (mapper) for (const [pattern, target] of Object.entries(mapper)) if (/\\\./.test(pattern) && /\b(png|jpe?g|gif|webp|svg|ttf|otf|woff2?|mp4|mp3)\b/i.test(pattern)) presetCovered.push(`moduleNameMapper '${pattern}' — asset stubbing is built in; delete.`);
|
|
428
|
+
else if (/^\^?@\/|\^~\/|\^src\//.test(pattern)) {
|
|
429
|
+
const aliasKey = pattern.replace(/[\^$]/g, "").replace(/\((\.\*|\.\+)\)\$?$/, "").replace(/\/$/, "");
|
|
430
|
+
const aliasTarget = String(target).replace(/^<rootDir>\/?/, "./").replace(/\/\$1$/, "").replace(/\/$/, "");
|
|
431
|
+
if (/[(){}?+*\\[\]]/.test(aliasKey) || /[(){}?+*\\[\]$]/.test(aliasTarget)) attention.push(`moduleNameMapper '${pattern}' → '${String(target)}' — map manually to resolve.alias (regex mappers need rewriting).`);
|
|
432
|
+
else {
|
|
433
|
+
aliasEntries.push(`${JSON.stringify(aliasKey)}: fileURLToPath(new URL(${JSON.stringify(aliasTarget)}, import.meta.url))`);
|
|
434
|
+
needsUrlImport = true;
|
|
435
|
+
automatic.push(`moduleNameMapper '${pattern}' → resolve.alias (absolute path).`);
|
|
436
|
+
}
|
|
437
|
+
} else attention.push(`moduleNameMapper '${pattern}' → '${String(target)}' — map manually to resolve.alias (regex mappers need rewriting).`);
|
|
438
|
+
const tip = take("transformIgnorePatterns");
|
|
439
|
+
if (tip?.length) {
|
|
440
|
+
const results = tip.map(extractAllowlistPackages);
|
|
441
|
+
const extracted = results.flatMap((r) => r.packages);
|
|
442
|
+
const unparseable = results.flatMap((r) => r.unparseable);
|
|
443
|
+
automatic.push(`transformIgnorePatterns (raw): ${JSON.stringify(tip)}`);
|
|
444
|
+
for (const entry of unparseable) attention.push(`transformIgnorePatterns entry '${entry}' — could not extract package names confidently; expand it by hand into reactNative({ transform: [...] }) if those packages ship untranspiled source.`);
|
|
445
|
+
if (extracted.length === 0 && unparseable.length === 0) attention.push(`transformIgnorePatterns: ${JSON.stringify(tip)} — could not extract an allowlist automatically; packages shipping untranspiled source go in reactNative({ transform: [...] }).`);
|
|
446
|
+
else for (const pkg of extracted) if (pkg === "react-native" || pkg.startsWith("@react-native")) automatic.push(`transformIgnorePatterns allows '${pkg}' — the native engine transforms RN itself; nothing to do.`);
|
|
447
|
+
else if (presetPkgs.has(pkg)) presetCovered.push(`transformIgnorePatterns allows '${pkg}' — shadowed by the auto-detected preset; nothing to do.`);
|
|
448
|
+
else if (autoInlined.has(pkg)) automatic.push(`transformIgnorePatterns allows '${pkg}' — declares react-native, so the engine compiles it automatically; nothing to do.`);
|
|
449
|
+
else {
|
|
450
|
+
transformPkgs.push(pkg);
|
|
451
|
+
automatic.push(`transformIgnorePatterns allows '${pkg}' → reactNative({ transform: [...] }).`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
const timeout = take("testTimeout");
|
|
455
|
+
if (typeof timeout === "number") {
|
|
456
|
+
testEntries.push(`testTimeout: ${timeout}`);
|
|
457
|
+
automatic.push(`testTimeout: ${timeout} → test.testTimeout.`);
|
|
458
|
+
}
|
|
459
|
+
const env = take("testEnvironment");
|
|
460
|
+
if (env && env !== "node") attention.push(`testEnvironment: '${env}' — vitest-native suites run under 'node'; review.`);
|
|
461
|
+
else handled.add("testEnvironment");
|
|
462
|
+
if (take("fakeTimers") !== void 0) attention.push(`fakeTimers — configure per-suite with vi.useFakeTimers() (the jest-compat shim covers jest.useFakeTimers()).`);
|
|
463
|
+
const testMatch = take("testMatch");
|
|
464
|
+
if (testMatch?.length) {
|
|
465
|
+
testEntries.push(`include: [${testMatch.map((g) => JSON.stringify(g.replace("<rootDir>/", ""))).join(", ")}]`);
|
|
466
|
+
automatic.push(`testMatch → test.include.`);
|
|
467
|
+
}
|
|
468
|
+
const ignore = take("testPathIgnorePatterns");
|
|
469
|
+
if (ignore?.length) attention.push(`testPathIgnorePatterns: ${JSON.stringify(ignore)} — move to test.exclude (glob syntax, not regex).`);
|
|
470
|
+
const coverageFrom = take("collectCoverageFrom");
|
|
471
|
+
if (coverageFrom?.length) {
|
|
472
|
+
testEntries.push(`coverage: { include: [${coverageFrom.map((g) => JSON.stringify(g.replace(/^<rootDir>\//, ""))).join(", ")}] }`);
|
|
473
|
+
automatic.push(`collectCoverageFrom → test.coverage.include (install @vitest/coverage-v8).`);
|
|
474
|
+
}
|
|
475
|
+
take("coveragePathIgnorePatterns");
|
|
476
|
+
take("coverageThreshold");
|
|
477
|
+
if (config.coveragePathIgnorePatterns || config.coverageThreshold) attention.push(`coverage settings — map onto test.coverage.{exclude,thresholds}.`);
|
|
478
|
+
for (const key of [
|
|
479
|
+
"moduleFileExtensions",
|
|
480
|
+
"maxWorkers",
|
|
481
|
+
"verbose",
|
|
482
|
+
"clearMocks",
|
|
483
|
+
"resetMocks",
|
|
484
|
+
"restoreMocks",
|
|
485
|
+
"collectCoverage",
|
|
486
|
+
"coverageDirectory",
|
|
487
|
+
"coverageReporters",
|
|
488
|
+
"cacheDirectory",
|
|
489
|
+
"haste",
|
|
490
|
+
"watchPlugins",
|
|
491
|
+
"transform",
|
|
492
|
+
"globals",
|
|
493
|
+
"roots",
|
|
494
|
+
"testRegex",
|
|
495
|
+
"snapshotSerializers",
|
|
496
|
+
"reporters",
|
|
497
|
+
"modulePathIgnorePatterns"
|
|
498
|
+
]) if (config[key] !== void 0) {
|
|
499
|
+
handled.add(key);
|
|
500
|
+
if (key === "transform") dropped.push(`transform — Babel/esbuild transforms are the plugin's job; dropped.`);
|
|
501
|
+
else if (key === "clearMocks" || key === "resetMocks" || key === "restoreMocks") {
|
|
502
|
+
automatic.push(`${key} → test.${key} (same name in Vitest).`);
|
|
503
|
+
testEntries.push(`${key}: ${JSON.stringify(config[key])}`);
|
|
504
|
+
} else if (key === "snapshotSerializers") attention.push(`snapshotSerializers — Vitest uses expect.addSnapshotSerializer; vitest-native ships one for RN trees.`);
|
|
505
|
+
else dropped.push(`${key} — no vitest-native equivalent needed; dropped.`);
|
|
506
|
+
}
|
|
507
|
+
for (const key of Object.keys(config)) if (!handled.has(key)) attention.push(`'${key}' — unrecognized Jest key; review manually.`);
|
|
508
|
+
}
|
|
509
|
+
const mocksDir = node_path.default.join(root, "__mocks__");
|
|
510
|
+
if (node_fs.default.existsSync(mocksDir)) for (const entry of node_fs.default.readdirSync(mocksDir)) {
|
|
511
|
+
const name = entry.replace(/\.(js|cjs|mjs|ts|tsx)$/, "");
|
|
512
|
+
const candidates = node_fs.default.statSync(node_path.default.join(mocksDir, entry)).isDirectory() ? node_fs.default.readdirSync(node_path.default.join(mocksDir, entry)).map((f) => `${name}/${f.replace(/\.(js|cjs|mjs|ts|tsx)$/, "")}`) : [name];
|
|
513
|
+
for (const candidate of candidates) if (presetPkgs.has(candidate)) {
|
|
514
|
+
const preset = require_preset_map.AUTO_DETECT_PRESETS[candidate];
|
|
515
|
+
presetCovered.push(`__mocks__/${candidate} — the ${preset} preset covers this; delete the manual mock.`);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const transformLine = transformPkgs.length ? `reactNative({ transform: [${transformPkgs.map((p) => JSON.stringify(p)).join(", ")}] })` : `reactNative()`;
|
|
519
|
+
return {
|
|
520
|
+
source,
|
|
521
|
+
automatic,
|
|
522
|
+
attention,
|
|
523
|
+
presetCovered,
|
|
524
|
+
dropped,
|
|
525
|
+
suggestedConfig: `import { defineConfig } from 'vitest/config'
|
|
526
|
+
import { reactNative } from 'vitest-native'
|
|
527
|
+
import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
|
|
528
|
+
${needsUrlImport ? "import { fileURLToPath } from 'node:url'\n" : ""}
|
|
529
|
+
export default defineConfig({
|
|
530
|
+
plugins: [${transformLine}, jestMockTransform()],
|
|
531
|
+
resolve: {
|
|
532
|
+
dedupe: ['react', 'react-test-renderer', 'react-is'],
|
|
533
|
+
alias: { ${aliasEntries.join(", ")} },
|
|
534
|
+
},
|
|
535
|
+
test: {
|
|
536
|
+
${testEntries.join(",\n ")},
|
|
537
|
+
setupFiles: [${setupFiles.join(", ")}],
|
|
538
|
+
},
|
|
539
|
+
})
|
|
540
|
+
`,
|
|
541
|
+
ok: source !== null
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
function renderMigrationReport(report) {
|
|
545
|
+
const lines = [];
|
|
546
|
+
if (!report.source) {
|
|
547
|
+
lines.push("✗ no Jest configuration found (package.json#jest or jest.config.{js,cjs,json}).", " Starting fresh? Run `vitest-native init` instead.");
|
|
548
|
+
return lines;
|
|
549
|
+
}
|
|
550
|
+
lines.push(`Analyzed ${report.source}`, "");
|
|
551
|
+
const section = (title, items) => {
|
|
552
|
+
if (!items.length) return;
|
|
553
|
+
lines.push(`${title}:`);
|
|
554
|
+
for (const i of items) lines.push(` • ${i}`);
|
|
555
|
+
lines.push("");
|
|
556
|
+
};
|
|
557
|
+
section("Mapped automatically", report.automatic);
|
|
558
|
+
section("Covered by presets — delete", report.presetCovered);
|
|
559
|
+
section("Needs your attention", report.attention);
|
|
560
|
+
section("Dropped (no equivalent needed)", report.dropped);
|
|
561
|
+
lines.push("Suggested vitest.config:", "");
|
|
562
|
+
lines.push(...report.suggestedConfig.split("\n").map((l) => ` ${l}`));
|
|
563
|
+
lines.push("Re-run with --write to save this config, then: npx vitest-native doctor && npx vitest");
|
|
564
|
+
return lines;
|
|
565
|
+
}
|
|
566
|
+
//#endregion
|
|
567
|
+
//#region src/cli/index.ts
|
|
568
|
+
/**
|
|
569
|
+
* vitest-native CLI: `init` (write a ready config), `doctor` (diagnose the
|
|
570
|
+
* environment), `migrate` (analyze a Jest config and report the mapping).
|
|
571
|
+
* Deliberately vitest-free at module load — it runs via npx outside any test
|
|
572
|
+
* process.
|
|
573
|
+
*/
|
|
574
|
+
const USAGE = `vitest-native — test React Native with Vitest
|
|
575
|
+
|
|
576
|
+
Usage:
|
|
577
|
+
vitest-native init [--jest-compat] [--force] write a ready-to-run vitest config
|
|
578
|
+
vitest-native doctor diagnose peers, engine, presets, RNTL/Node
|
|
579
|
+
vitest-native migrate [--write] [--force] analyze jest config → migration report
|
|
580
|
+
(--write also saves the suggested config)
|
|
581
|
+
Options:
|
|
582
|
+
--root <dir> project root (default: cwd)
|
|
583
|
+
--help this text
|
|
584
|
+
|
|
585
|
+
Docs: https://danfry1.github.io/vitest-native/`;
|
|
586
|
+
function main(argv, log = console.log) {
|
|
587
|
+
const args = argv.filter((a) => a !== "--");
|
|
588
|
+
const command = args.find((a, i) => !a.startsWith("-") && args[i - 1] !== "--root");
|
|
589
|
+
const has = (flag) => args.includes(flag);
|
|
590
|
+
const rootIdx = args.indexOf("--root");
|
|
591
|
+
const root = node_path.default.resolve(rootIdx !== -1 ? args[rootIdx + 1] ?? "." : ".");
|
|
592
|
+
if (has("--help") || has("-h")) {
|
|
593
|
+
log(USAGE);
|
|
594
|
+
return 0;
|
|
595
|
+
}
|
|
596
|
+
if (!command) {
|
|
597
|
+
log(USAGE);
|
|
598
|
+
return 1;
|
|
599
|
+
}
|
|
600
|
+
if (!node_fs.default.existsSync(node_path.default.join(root, "package.json"))) {
|
|
601
|
+
log(`✗ no package.json at ${root} — run from a project root or pass --root.`);
|
|
602
|
+
return 1;
|
|
603
|
+
}
|
|
604
|
+
switch (command) {
|
|
605
|
+
case "doctor": {
|
|
606
|
+
const result = runDoctor(root);
|
|
607
|
+
for (const line of result.lines) log(line);
|
|
608
|
+
return result.ok ? 0 : 1;
|
|
609
|
+
}
|
|
610
|
+
case "init": {
|
|
611
|
+
const result = runInit(root, {
|
|
612
|
+
jestCompat: has("--jest-compat"),
|
|
613
|
+
force: has("--force")
|
|
614
|
+
});
|
|
615
|
+
for (const line of result.lines) log(line);
|
|
616
|
+
return result.ok ? 0 : 1;
|
|
617
|
+
}
|
|
618
|
+
case "migrate": {
|
|
619
|
+
const report = analyzeJestConfig(root);
|
|
620
|
+
for (const line of renderMigrationReport(report)) log(line);
|
|
621
|
+
if (report.ok && has("--write")) {
|
|
622
|
+
const init = runInit(root, { force: has("--force") });
|
|
623
|
+
if (!init.ok) {
|
|
624
|
+
for (const line of init.lines) log(line);
|
|
625
|
+
return 1;
|
|
626
|
+
}
|
|
627
|
+
const target = node_path.default.join(root, init.wrote);
|
|
628
|
+
node_fs.default.writeFileSync(target, report.suggestedConfig);
|
|
629
|
+
log(`✓ wrote ${init.wrote} from the analysis above.`);
|
|
630
|
+
}
|
|
631
|
+
return report.ok ? 0 : 1;
|
|
632
|
+
}
|
|
633
|
+
default:
|
|
634
|
+
log(`✗ unknown command '${command}'.`);
|
|
635
|
+
log(USAGE);
|
|
636
|
+
return 1;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
const entry = process.argv[1] ? node_path.default.basename(process.argv[1]) : "";
|
|
640
|
+
if (entry === "cli.mjs" || entry === "cli.cjs" || entry === "vitest-native") process.exit(main(process.argv.slice(2)));
|
|
641
|
+
//#endregion
|
|
642
|
+
exports.main = main;
|
package/dist/cli.d.cts
ADDED
package/dist/cli.d.mts
ADDED