@nx/vitest 23.1.0 → 23.1.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.
- package/dist/src/executors/test/lib/utils.js +12 -3
- package/dist/src/generators/configuration/configuration.js +161 -9
- package/dist/src/plugins/plugin.d.ts +21 -0
- package/dist/src/plugins/plugin.js +233 -13
- package/dist/src/utils/executor-utils.d.ts +2 -1
- package/dist/src/utils/executor-utils.js +4 -3
- package/package.json +5 -5
|
@@ -7,6 +7,7 @@ const devkit_1 = require("@nx/devkit");
|
|
|
7
7
|
const options_utils_1 = require("../../../utils/options-utils");
|
|
8
8
|
const path_1 = require("path");
|
|
9
9
|
const executor_utils_1 = require("../../../utils/executor-utils");
|
|
10
|
+
const devkit_internals_1 = require("nx/src/devkit-internals");
|
|
10
11
|
async function getOptions(options, context, projectRoot) {
|
|
11
12
|
// Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.
|
|
12
13
|
const { loadConfigFromFile } = await (0, executor_utils_1.loadViteDynamicImport)();
|
|
@@ -49,10 +50,18 @@ async function getOptions(options, context, projectRoot) {
|
|
|
49
50
|
'--': _dashdash, color: _color, w: _w,
|
|
50
51
|
// Pass through any additional Vitest options
|
|
51
52
|
...passThroughOptions } = normalizedExtraArgs;
|
|
53
|
+
// Vitest keeps the UI/browser server alive only in watch mode and has no
|
|
54
|
+
// --ui -> watch link, so a run-once `nx test --ui` tears the UI down right
|
|
55
|
+
// after the run. When --ui is requested from an interactive, non-CI terminal,
|
|
56
|
+
// default watch on so the UI stays open; bare runs and CI stay run-once so
|
|
57
|
+
// `nx run-many`/`affected` don't hang. An explicit CLI --watch/--no-watch or a
|
|
58
|
+
// config `test.watch` still takes precedence.
|
|
59
|
+
const uiRequested = passThroughOptions.ui === true;
|
|
60
|
+
const watchForUi = uiRequested && !!process.stdin.isTTY && !(0, devkit_internals_1.isCI)();
|
|
52
61
|
return {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
62
|
+
watch: watch ??
|
|
63
|
+
resolved?.config?.['test']?.watch ??
|
|
64
|
+
watchForUi,
|
|
56
65
|
// Pass through any additional Vitest options
|
|
57
66
|
...passThroughOptions,
|
|
58
67
|
// This should not be needed as it's going to be set in vite.config.ts
|
|
@@ -16,6 +16,7 @@ const version_utils_1 = require("../../utils/version-utils");
|
|
|
16
16
|
const versions_1 = require("../../utils/versions");
|
|
17
17
|
const assert_supported_vitest_version_1 = require("../../utils/assert-supported-vitest-version");
|
|
18
18
|
const semver_1 = require("semver");
|
|
19
|
+
let ts;
|
|
19
20
|
/**
|
|
20
21
|
* Determines whether to use vitest.config.mts instead of vite.config.mts.
|
|
21
22
|
* Returns true for new non-framework projects that don't already have a vite.config.
|
|
@@ -176,15 +177,86 @@ getTestBed().initTestEnvironment(
|
|
|
176
177
|
const installDependenciesTask = (0, devkit_1.addDependenciesToPackageJson)(tree, {}, devDependencies, undefined, true);
|
|
177
178
|
tasks.push(installDependenciesTask);
|
|
178
179
|
}
|
|
179
|
-
// Setup
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
180
|
+
// Setup the root config aggregating the project configs. Vitest 4 removed
|
|
181
|
+
// workspace files in favor of inlining the projects into a root vitest.config
|
|
182
|
+
// via `test.projects` (https://vitest.dev/guide/migration.html#workspace-is-replaced-with-projects).
|
|
183
|
+
// Emit that shape for vitest 4+ and when the installed version can't be
|
|
184
|
+
// detected (new installs resolve to v4); vitest 3 keeps the workspace file.
|
|
185
|
+
if (!isRootProject) {
|
|
186
|
+
const projectGlobs = `'**/vite.config.{mjs,js,ts,mts}', '**/vitest.config.{mjs,js,ts,mts}'`;
|
|
187
|
+
const vitestMajorVersion = (0, versions_1.getInstalledVitestMajorVersion)(tree);
|
|
188
|
+
if (vitestMajorVersion === null || vitestMajorVersion >= 4) {
|
|
189
|
+
const hasWorkspaceFile = ['ts', 'js', 'json'].some((ext) => tree.exists(`vitest.workspace.${ext}`) ||
|
|
190
|
+
tree.exists(`vitest.projects.${ext}`));
|
|
191
|
+
const rootVitestConfig = findRootConfig(tree, 'vitest.config');
|
|
192
|
+
const rootViteConfig = findRootConfig(tree, 'vite.config');
|
|
193
|
+
if (hasWorkspaceFile) {
|
|
194
|
+
// A workspace/projects file already defines the project set and the
|
|
195
|
+
// vitest 4 migration converts it; leave it untouched.
|
|
196
|
+
}
|
|
197
|
+
else if (rootVitestConfig) {
|
|
198
|
+
// A root vitest.config.* wins vitest's config resolution, so we can
|
|
199
|
+
// neither add a competing aggregator nor safely rewrite it. Warn when it
|
|
200
|
+
// doesn't aggregate, or when its shape can't be read statically, since
|
|
201
|
+
// the new project would otherwise be silently absent from
|
|
202
|
+
// workspace-level vitest runs.
|
|
203
|
+
const declaresProjects = rootConfigDeclaresProjects(tree, rootVitestConfig);
|
|
204
|
+
if (declaresProjects === 'missing') {
|
|
205
|
+
devkit_1.logger.warn(`Found a root "${rootVitestConfig}" without a \`test.projects\` entry. ` +
|
|
206
|
+
`The "${schema.project}" project won't be part of workspace-level ` +
|
|
207
|
+
`vitest runs until you add its config file to \`test.projects\` there.`);
|
|
208
|
+
}
|
|
209
|
+
else if (declaresProjects === 'unknown') {
|
|
210
|
+
devkit_1.logger.warn(`Found a root "${rootVitestConfig}" whose test setup couldn't be ` +
|
|
211
|
+
`analyzed. If the "${schema.project}" project isn't picked up by ` +
|
|
212
|
+
`workspace-level vitest runs, add its config file to ` +
|
|
213
|
+
`\`test.projects\` there.`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
else if (rootViteConfig) {
|
|
217
|
+
// A root vite.config.* is vitest's config today. Writing a
|
|
218
|
+
// vitest.config.* would win resolution and shadow it, dropping the vite
|
|
219
|
+
// settings (aliases, plugins) from vitest runs, and projects don't
|
|
220
|
+
// inherit those from a root aggregator either. Leave it in place.
|
|
221
|
+
const declaresProjects = rootConfigDeclaresProjects(tree, rootViteConfig);
|
|
222
|
+
if (declaresProjects === 'missing') {
|
|
223
|
+
devkit_1.logger.warn(`Found a root "${rootViteConfig}" without a \`test.projects\` entry. ` +
|
|
224
|
+
`The "${schema.project}" project runs through that root config, so ` +
|
|
225
|
+
`its own vitest configuration (e.g. \`environment\`, \`setupFiles\`) ` +
|
|
226
|
+
`won't apply. Add its config file to a \`test.projects\` entry there ` +
|
|
227
|
+
`to run it with its own configuration.`);
|
|
228
|
+
}
|
|
229
|
+
else if (declaresProjects === 'unknown') {
|
|
230
|
+
devkit_1.logger.warn(`Found a root "${rootViteConfig}" whose test setup couldn't be ` +
|
|
231
|
+
`analyzed. If the "${schema.project}" project isn't picked up by ` +
|
|
232
|
+
`workspace-level vitest runs, add its config file to ` +
|
|
233
|
+
`\`test.projects\` there.`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
// No root config exists, so emit the aggregator. Its projects glob
|
|
238
|
+
// matches every vite/vitest config, including this file itself and any
|
|
239
|
+
// root vite.config added later; exclude both so neither is resolved as
|
|
240
|
+
// an extra project that, carrying no `include`, re-runs every spec via
|
|
241
|
+
// the default glob.
|
|
242
|
+
tree.write('vitest.config.ts', `import { defineConfig } from 'vitest/config';
|
|
243
|
+
|
|
244
|
+
export default defineConfig({
|
|
245
|
+
test: {
|
|
246
|
+
projects: [${projectGlobs}, '!vitest.config.{mjs,js,ts,mts}', '!vite.config.{mjs,js,ts,mts}'],
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
else if (!tree.exists(`vitest.workspace.ts`) &&
|
|
253
|
+
!tree.exists(`vitest.workspace.js`) &&
|
|
254
|
+
!tree.exists(`vitest.workspace.json`) &&
|
|
255
|
+
!tree.exists(`vitest.projects.ts`) &&
|
|
256
|
+
!tree.exists(`vitest.projects.js`) &&
|
|
257
|
+
!tree.exists(`vitest.projects.json`)) {
|
|
258
|
+
tree.write('vitest.workspace.ts', `export default [${projectGlobs}];`);
|
|
259
|
+
}
|
|
188
260
|
}
|
|
189
261
|
if (!schema.skipFormat) {
|
|
190
262
|
await (0, devkit_1.formatFiles)(tree);
|
|
@@ -369,4 +441,84 @@ function findTestDefault(td, target) {
|
|
|
369
441
|
}
|
|
370
442
|
return value;
|
|
371
443
|
}
|
|
444
|
+
function findRootConfig(tree, name) {
|
|
445
|
+
for (const ext of ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs']) {
|
|
446
|
+
const candidate = `${name}.${ext}`;
|
|
447
|
+
if (tree.exists(candidate)) {
|
|
448
|
+
return candidate;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return undefined;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Classifies a root config's default export by whether it already aggregates
|
|
455
|
+
* projects via `test.projects` (or the vitest 3 `test.workspace`):
|
|
456
|
+
* - `'declares'`: it aggregates projects.
|
|
457
|
+
* - `'missing'`: it's a readable object config with no such aggregation.
|
|
458
|
+
* - `'unknown'`: the shape can't be read statically (dynamic/function configs,
|
|
459
|
+
* spreads), where the safe move is to leave the config untouched rather than
|
|
460
|
+
* shadow it.
|
|
461
|
+
*/
|
|
462
|
+
function rootConfigDeclaresProjects(tree, configPath) {
|
|
463
|
+
ts ??= (0, internal_2.ensureTypescript)();
|
|
464
|
+
const { tsquery } = require('@phenomnomnominal/tsquery');
|
|
465
|
+
let sourceFile;
|
|
466
|
+
try {
|
|
467
|
+
sourceFile = tsquery.ast(tree.read(configPath, 'utf-8'));
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
return 'unknown';
|
|
471
|
+
}
|
|
472
|
+
const exportAssignment = sourceFile.statements.find((s) => ts.isExportAssignment(s) && !s.isExportEquals);
|
|
473
|
+
if (!exportAssignment) {
|
|
474
|
+
return 'unknown';
|
|
475
|
+
}
|
|
476
|
+
let expression = unwrapExpression(exportAssignment.expression);
|
|
477
|
+
// Unwrap a single-argument config wrapper such as `defineConfig(...)`.
|
|
478
|
+
if (ts.isCallExpression(expression) &&
|
|
479
|
+
ts.isIdentifier(expression.expression) &&
|
|
480
|
+
expression.arguments.length === 1) {
|
|
481
|
+
expression = unwrapExpression(expression.arguments[0]);
|
|
482
|
+
}
|
|
483
|
+
if (!ts.isObjectLiteralExpression(expression)) {
|
|
484
|
+
return 'unknown';
|
|
485
|
+
}
|
|
486
|
+
// A spread could hide a `test` block we can't see.
|
|
487
|
+
if (expression.properties.some((p) => ts.isSpreadAssignment(p))) {
|
|
488
|
+
return 'unknown';
|
|
489
|
+
}
|
|
490
|
+
const testProperty = findObjectProperty(expression, 'test');
|
|
491
|
+
if (!testProperty) {
|
|
492
|
+
return 'missing';
|
|
493
|
+
}
|
|
494
|
+
if (!ts.isObjectLiteralExpression(testProperty.initializer)) {
|
|
495
|
+
return 'unknown';
|
|
496
|
+
}
|
|
497
|
+
const testObject = testProperty.initializer;
|
|
498
|
+
if (testObject.properties.some((p) => ts.isSpreadAssignment(p))) {
|
|
499
|
+
return 'unknown';
|
|
500
|
+
}
|
|
501
|
+
return findObjectProperty(testObject, 'projects') ||
|
|
502
|
+
findObjectProperty(testObject, 'workspace')
|
|
503
|
+
? 'declares'
|
|
504
|
+
: 'missing';
|
|
505
|
+
}
|
|
506
|
+
function unwrapExpression(expression) {
|
|
507
|
+
while (ts.isAsExpression(expression) ||
|
|
508
|
+
ts.isSatisfiesExpression(expression) ||
|
|
509
|
+
ts.isParenthesizedExpression(expression)) {
|
|
510
|
+
expression = expression.expression;
|
|
511
|
+
}
|
|
512
|
+
return expression;
|
|
513
|
+
}
|
|
514
|
+
function findObjectProperty(objectLiteral, name) {
|
|
515
|
+
for (const property of objectLiteral.properties) {
|
|
516
|
+
if (ts.isPropertyAssignment(property) &&
|
|
517
|
+
(ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
|
|
518
|
+
property.name.text === name) {
|
|
519
|
+
return property;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return undefined;
|
|
523
|
+
}
|
|
372
524
|
exports.default = configurationGenerator;
|
|
@@ -15,6 +15,27 @@ export interface VitestPluginOptions {
|
|
|
15
15
|
* - 'run': Tests run once and exit
|
|
16
16
|
*/
|
|
17
17
|
testMode?: 'watch' | 'run';
|
|
18
|
+
/**
|
|
19
|
+
* How atomized test files (the `ciTargetName` targets) are discovered.
|
|
20
|
+
* - 'glob' (default): enumerate specs with a glob that mirrors Vitest's own
|
|
21
|
+
* resolution instead of booting Vitest per project. Booting Vitest starts a
|
|
22
|
+
* Vite dev server and runs the config's plugin hooks, so the glob is faster
|
|
23
|
+
* during graph creation. The glob reads the Nx workspace file index, so
|
|
24
|
+
* files ignored by `.gitignore`/`.nxignore` are never enumerated even when
|
|
25
|
+
* Vitest itself would run them.
|
|
26
|
+
* - 'vitest': always enumerate through Vitest.
|
|
27
|
+
*
|
|
28
|
+
* Configs a glob cannot reproduce faithfully still boot Vitest automatically
|
|
29
|
+
* even under 'glob': `test.projects`/`test.workspace` (inline or an
|
|
30
|
+
* auto-loaded `vitest.workspace.*`/`vitest.projects.*` sibling file), plugins
|
|
31
|
+
* with a `configureVitest` hook, `test.changed`/`test.related`, enabled
|
|
32
|
+
* browser `instances` that set their own include/exclude/includeSource/dir,
|
|
33
|
+
* and `include`, `exclude`, `includeSource`, or `typecheck` include/exclude
|
|
34
|
+
* patterns the workspace glob reads differently (absolute paths, a trailing
|
|
35
|
+
* `/`, or an `!(...)` extglob, each optionally negated).
|
|
36
|
+
* @default 'glob'
|
|
37
|
+
*/
|
|
38
|
+
discoverTestFiles?: 'glob' | 'vitest';
|
|
18
39
|
}
|
|
19
40
|
/**
|
|
20
41
|
* @deprecated The 'createDependencies' function is now a no-op. This functionality is included in 'createNodesV2'.
|
|
@@ -6,10 +6,12 @@ const devkit_1 = require("@nx/devkit");
|
|
|
6
6
|
const js_1 = require("@nx/js");
|
|
7
7
|
const internal_2 = require("@nx/js/internal");
|
|
8
8
|
const node_fs_1 = require("node:fs");
|
|
9
|
+
const promises_1 = require("node:fs/promises");
|
|
9
10
|
const node_path_1 = require("node:path");
|
|
10
11
|
const file_hasher_1 = require("nx/src/hasher/file-hasher");
|
|
11
12
|
const cache_directory_1 = require("nx/src/utils/cache-directory");
|
|
12
13
|
const plugins_1 = require("nx/src/utils/plugins");
|
|
14
|
+
const workspace_context_1 = require("nx/src/utils/workspace-context");
|
|
13
15
|
const executor_utils_1 = require("../utils/executor-utils");
|
|
14
16
|
/**
|
|
15
17
|
* @deprecated The 'createDependencies' function is now a no-op. This functionality is included in 'createNodesV2'.
|
|
@@ -53,9 +55,18 @@ exports.createNodes = [
|
|
|
53
55
|
// for different config files.
|
|
54
56
|
const hash = hashes[idx] + configFile;
|
|
55
57
|
if (!targetsCache.has(hash)) {
|
|
56
|
-
|
|
58
|
+
const result = await buildVitestTargets(configFile, projectRoot, normalizedOptions, context, pmc, tsconfigChainsByProjectRoot.get(projectRoot) ?? []);
|
|
59
|
+
// Cache the result even when it's null (a root orchestrator config)
|
|
60
|
+
// so the config isn't re-resolved on every project-graph build.
|
|
61
|
+
targetsCache.set(hash, result);
|
|
57
62
|
}
|
|
58
|
-
const
|
|
63
|
+
const cached = targetsCache.get(hash);
|
|
64
|
+
// `buildVitestTargets` returns null for a root orchestrator config
|
|
65
|
+
// that must not become a project; register no node for it.
|
|
66
|
+
if (!cached) {
|
|
67
|
+
return { projects: {} };
|
|
68
|
+
}
|
|
69
|
+
const { projectType, metadata, targets } = cached;
|
|
59
70
|
const project = {
|
|
60
71
|
root: projectRoot,
|
|
61
72
|
targets,
|
|
@@ -115,14 +126,14 @@ async function buildVitestTargets(configFilePath, projectRoot, options, context,
|
|
|
115
126
|
configFile: absoluteConfigFilePath,
|
|
116
127
|
mode: 'development',
|
|
117
128
|
}, 'build');
|
|
118
|
-
//
|
|
119
|
-
//
|
|
129
|
+
// A root config that aggregates project configs via `test.projects` is just an
|
|
130
|
+
// orchestrator; the actual tests live in the individual project configs. Skip it
|
|
131
|
+
// entirely so it does not register a project rooted at the workspace root (which
|
|
132
|
+
// would, for example, make `nx format` treat the whole workspace as one project).
|
|
120
133
|
const isWorkspaceRoot = projectRoot === '.';
|
|
121
|
-
|
|
122
|
-
// "nodenext". Vite 8's rolldown types break vitest's test augmentation.
|
|
123
|
-
const hasProjectsProperty = Array.isArray(viteBuildConfig?.test?.projects);
|
|
134
|
+
const hasProjectsProperty = Array.isArray(viteBuildConfig.test?.projects);
|
|
124
135
|
if (isWorkspaceRoot && hasProjectsProperty) {
|
|
125
|
-
return
|
|
136
|
+
return null;
|
|
126
137
|
}
|
|
127
138
|
let metadata = {};
|
|
128
139
|
const { testOutputs, hasTest } = getOutputs(viteBuildConfig, projectRoot, context.workspaceRoot);
|
|
@@ -130,8 +141,7 @@ async function buildVitestTargets(configFilePath, projectRoot, options, context,
|
|
|
130
141
|
const targets = {};
|
|
131
142
|
// if file is vitest.config or vite.config has definition for test, create targets for test and/or atomized tests
|
|
132
143
|
if (configFilePath.includes('vitest.config') || hasTest) {
|
|
133
|
-
const isTypecheckEnabled = !!viteBuildConfig
|
|
134
|
-
?.enabled;
|
|
144
|
+
const isTypecheckEnabled = !!viteBuildConfig.test?.typecheck?.enabled;
|
|
135
145
|
targets[options.testTargetName] = await testTarget(namedInputs, testOutputs, projectRoot, options.testMode, pmc, isTypecheckEnabled, tsconfigInputs);
|
|
136
146
|
if (options.ciTargetName) {
|
|
137
147
|
const groupName = options.ciGroupName ?? (0, plugins_1.deriveGroupNameFromTarget)(options.ciTargetName);
|
|
@@ -142,7 +152,24 @@ async function buildVitestTargets(configFilePath, projectRoot, options, context,
|
|
|
142
152
|
[groupName]: targetGroup,
|
|
143
153
|
},
|
|
144
154
|
};
|
|
145
|
-
|
|
155
|
+
// Not normalizing in normalizeOptions since it also affects the options
|
|
156
|
+
// computed for convert-to-inferred.
|
|
157
|
+
const useGlobDiscovery = (options.discoverTestFiles ?? 'glob') !== 'vitest';
|
|
158
|
+
// Both discovery paths read the serve-resolved config: Vitest runs tests
|
|
159
|
+
// through a Vite server (the `serve` command), so `apply: 'serve'`
|
|
160
|
+
// plugins and command-sensitive `test` options (include/exclude and
|
|
161
|
+
// `dir`) are absent from the build resolution used above for outputs.
|
|
162
|
+
// Resolve under `mode: 'test'` to match Vitest, which defaults the Vite
|
|
163
|
+
// mode to 'test'; a config that branches on `command`/`mode` would
|
|
164
|
+
// otherwise enumerate a different spec set here than at test time.
|
|
165
|
+
const viteServeConfig = await resolveConfig({
|
|
166
|
+
configFile: absoluteConfigFilePath,
|
|
167
|
+
mode: 'test',
|
|
168
|
+
}, 'serve');
|
|
169
|
+
const projectRootRelativeTestPaths = await getTestPathsRelativeToProjectRoot(projectRoot, context.workspaceRoot,
|
|
170
|
+
// Only the glob path reads this config; the opt-out path forces the
|
|
171
|
+
// runtime by receiving no config, and takes `test.dir` separately.
|
|
172
|
+
useGlobDiscovery ? viteServeConfig : undefined, viteServeConfig.test?.dir);
|
|
146
173
|
for (const relativePath of projectRootRelativeTestPaths) {
|
|
147
174
|
if (relativePath.includes('../')) {
|
|
148
175
|
throw new Error('@nx/vitest attempted to run tests outside of the project root. This is not supported and should not happen. Please open an issue at https://github.com/nrwl/nx/issues/new/choose with the following information:\n\n' +
|
|
@@ -392,12 +419,205 @@ function checkIfConfigFileShouldBeProject(projectRoot, context) {
|
|
|
392
419
|
}
|
|
393
420
|
return true;
|
|
394
421
|
}
|
|
395
|
-
async function getTestPathsRelativeToProjectRoot(projectRoot, workspaceRoot
|
|
422
|
+
async function getTestPathsRelativeToProjectRoot(projectRoot, workspaceRoot, viteConfig,
|
|
423
|
+
// Serve-resolved `test.dir` (the command Vitest runs under). Only used on the
|
|
424
|
+
// opt-out path below, which receives no `viteConfig` to read it from.
|
|
425
|
+
optOutTestDir) {
|
|
396
426
|
const fullProjectRoot = (0, node_path_1.join)(workspaceRoot, projectRoot);
|
|
427
|
+
// `viteConfig` is resolved only when glob discovery is requested; its absence
|
|
428
|
+
// means the runtime path was selected (`discoverTestFiles: 'vitest'`).
|
|
429
|
+
if (viteConfig) {
|
|
430
|
+
const test = viteConfig.test ?? {};
|
|
431
|
+
if (!configRequiresVitestRuntime(test, viteConfig, fullProjectRoot)) {
|
|
432
|
+
return globTestPathsRelativeToProjectRoot(test, workspaceRoot, projectRoot, fullProjectRoot);
|
|
433
|
+
}
|
|
434
|
+
return getTestPathsViaVitestRuntime(fullProjectRoot, projectRoot, test.dir);
|
|
435
|
+
}
|
|
436
|
+
return getTestPathsViaVitestRuntime(fullProjectRoot, projectRoot, optOutTestDir);
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* The directory Vitest enumerates from: `test.dir` when set, else the project
|
|
440
|
+
* root. Vitest resolves a relative `test.dir` against the working directory,
|
|
441
|
+
* which for both the `test` and atomized targets is the project root.
|
|
442
|
+
*/
|
|
443
|
+
function resolveTestDir(fullProjectRoot, testDir) {
|
|
444
|
+
return testDir ? (0, node_path_1.resolve)(fullProjectRoot, testDir) : fullProjectRoot;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Enumerates a project's test files by mirroring Vitest's own resolution with
|
|
448
|
+
* a glob. Vitest globs `test.include` and `test.includeSource` (both skipped
|
|
449
|
+
* when typecheck is enabled with `only`, the latter also kept only when the
|
|
450
|
+
* file contains an in-source test) plus `test.typecheck.include` (when
|
|
451
|
+
* typecheck is enabled), each minus the relevant `exclude`, from `test.dir`
|
|
452
|
+
* when set and the project root otherwise. Defaults come from the installed
|
|
453
|
+
* Vitest so they track the user's version. Globbing goes through the Nx
|
|
454
|
+
* workspace context (the daemon-cached file index), so files ignored by
|
|
455
|
+
* `.gitignore`/`.nxignore` are never candidates. Callers must first confirm the
|
|
456
|
+
* config is reproducible with a glob via `configRequiresVitestRuntime`.
|
|
457
|
+
*/
|
|
458
|
+
async function globTestPathsRelativeToProjectRoot(test, workspaceRoot, projectRoot, fullProjectRoot) {
|
|
459
|
+
const { configDefaults } = await (0, executor_utils_1.loadVitestConfigDynamicImport)();
|
|
460
|
+
const exclude = test.exclude ?? configDefaults.exclude;
|
|
461
|
+
const typecheck = test.typecheck;
|
|
462
|
+
const typecheckOnly = !!(typecheck?.enabled && typecheck?.only);
|
|
463
|
+
// The workspace context matches workspace-relative paths, while the config's
|
|
464
|
+
// patterns are relative to the directory Vitest enumerates from; anchor them
|
|
465
|
+
// to it.
|
|
466
|
+
const scanRoot = test.dir
|
|
467
|
+
? (0, devkit_1.normalizePath)((0, node_path_1.relative)(workspaceRoot, resolveTestDir(fullProjectRoot, test.dir)))
|
|
468
|
+
: projectRoot;
|
|
469
|
+
// The workspace context only reads `!` at index 0, so a negated pattern has
|
|
470
|
+
// to be re-prefixed rather than anchored as-is.
|
|
471
|
+
const anchor = (pattern) => isNegatedPattern(pattern)
|
|
472
|
+
? `!${(0, devkit_1.joinPathFragments)(scanRoot, pattern.slice(1))}`
|
|
473
|
+
: (0, devkit_1.joinPathFragments)(scanRoot, pattern);
|
|
474
|
+
const globProjectFiles = (include, ignore) => {
|
|
475
|
+
// The workspace context treats an all-negated (or empty) include set as
|
|
476
|
+
// "match everything" (it inverts to the exclude set), while Vitest
|
|
477
|
+
// enumerates nothing. Match Vitest: without a positive entry there is
|
|
478
|
+
// nothing to enumerate.
|
|
479
|
+
if (!include.some((pattern) => !isNegatedPattern(pattern))) {
|
|
480
|
+
return Promise.resolve([]);
|
|
481
|
+
}
|
|
482
|
+
return (0, workspace_context_1.globWithWorkspaceContext)(workspaceRoot, include.map(anchor),
|
|
483
|
+
// Vitest discards a negated `exclude` entry; forwarding it would turn the
|
|
484
|
+
// exclude set into an allowlist.
|
|
485
|
+
ignore.filter((pattern) => !isNegatedPattern(pattern)).map(anchor));
|
|
486
|
+
};
|
|
487
|
+
// Regular and type tests are independent walks; run them together.
|
|
488
|
+
const globJobs = [];
|
|
489
|
+
// Typecheck enabled with `only` makes Vitest run only type tests, so skip
|
|
490
|
+
// regular tests.
|
|
491
|
+
if (!typecheckOnly) {
|
|
492
|
+
const include = test.include ?? configDefaults.include;
|
|
493
|
+
globJobs.push(globProjectFiles(include, exclude));
|
|
494
|
+
}
|
|
495
|
+
if (typecheck?.enabled) {
|
|
496
|
+
const include = typecheck.include ?? configDefaults.typecheck.include;
|
|
497
|
+
const ignore = typecheck.exclude ?? configDefaults.typecheck.exclude;
|
|
498
|
+
globJobs.push(globProjectFiles(include, ignore));
|
|
499
|
+
}
|
|
500
|
+
const matches = new Set();
|
|
501
|
+
for (const files of await Promise.all(globJobs)) {
|
|
502
|
+
for (const file of files)
|
|
503
|
+
matches.add(file);
|
|
504
|
+
}
|
|
505
|
+
// In-source tests: only files that actually contain a test are included.
|
|
506
|
+
// Typecheck enabled with `only` makes Vitest run only type tests, so skip
|
|
507
|
+
// these too.
|
|
508
|
+
if (!typecheckOnly && test.includeSource?.length) {
|
|
509
|
+
const sourceFiles = await globProjectFiles(test.includeSource, exclude);
|
|
510
|
+
// The candidate set can be the whole `src` tree, so read in bounded
|
|
511
|
+
// batches; an unbounded Promise.all over every file risks EMFILE.
|
|
512
|
+
const readConcurrency = 25;
|
|
513
|
+
for (let i = 0; i < sourceFiles.length; i += readConcurrency) {
|
|
514
|
+
const inSourceMatches = await Promise.all(sourceFiles.slice(i, i + readConcurrency).map(async (file) => {
|
|
515
|
+
// Vitest tolerates unreadable in-source candidates and skips them;
|
|
516
|
+
// match that so a permission error or TOCTOU race can't abort graph
|
|
517
|
+
// creation.
|
|
518
|
+
try {
|
|
519
|
+
const content = await (0, promises_1.readFile)((0, node_path_1.join)(workspaceRoot, file), 'utf-8');
|
|
520
|
+
return content.includes('import.meta.vitest') ? file : null;
|
|
521
|
+
}
|
|
522
|
+
catch {
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
}));
|
|
526
|
+
for (const file of inSourceMatches) {
|
|
527
|
+
if (file)
|
|
528
|
+
matches.add(file);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
// The workspace context returns workspace-relative paths, so re-relativize
|
|
533
|
+
// them to the project root. An `include` pattern (`../lib2/**`) or an
|
|
534
|
+
// out-of-project `test.dir` can land outside the project root, so drop what
|
|
535
|
+
// does, matching the runtime path.
|
|
536
|
+
return [...matches]
|
|
537
|
+
.map((file) => (0, devkit_1.normalizePath)((0, node_path_1.relative)(projectRoot, file)))
|
|
538
|
+
.filter((file) => !file.startsWith('../'))
|
|
539
|
+
.sort();
|
|
540
|
+
}
|
|
541
|
+
// Vitest reads a leading `!` as a negation, except when it opens an extglob
|
|
542
|
+
// (`!(...)`), which the runtime gate routes away before discovery reaches here.
|
|
543
|
+
function isNegatedPattern(pattern) {
|
|
544
|
+
return pattern.startsWith('!') && !pattern.startsWith('!(');
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Whether the workspace context resolves a pattern differently than Vitest.
|
|
548
|
+
* Anchoring rewrites an absolute pattern into a project-relative one that
|
|
549
|
+
* enumerates the wrong location; a trailing `/` becomes a recursive directory
|
|
550
|
+
* match where Vitest (globbing with `expandDirectories: false`) matches
|
|
551
|
+
* nothing; and `!(...)` converts to an include plus literal exclusions that
|
|
552
|
+
* reproduces Vitest's extglob only for some shapes. A leading `!` is stripped
|
|
553
|
+
* first so a negated form of any of these still routes to the runtime.
|
|
554
|
+
*/
|
|
555
|
+
function patternRequiresVitestRuntime(pattern) {
|
|
556
|
+
const bare = isNegatedPattern(pattern) ? pattern.slice(1) : pattern;
|
|
557
|
+
return (0, node_path_1.isAbsolute)(bare) || bare.endsWith('/') || bare.includes('!(');
|
|
558
|
+
}
|
|
559
|
+
// Sibling files Vitest 3 auto-loads to define sub-projects even when the config
|
|
560
|
+
// object declares none. Removed in Vitest 4 in favor of inline `test.projects`.
|
|
561
|
+
const vitestWorkspaceFiles = ['vitest.workspace', 'vitest.projects'].flatMap((name) => ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json'].map((ext) => `${name}.${ext}`));
|
|
562
|
+
/**
|
|
563
|
+
* Whether a config's test discovery cannot be faithfully reproduced with a
|
|
564
|
+
* glob, so enumeration must go through Vitest itself.
|
|
565
|
+
*/
|
|
566
|
+
function configRequiresVitestRuntime(
|
|
567
|
+
// `workspace` (removed in Vitest 4) and the CLI-only `changed`/`related`
|
|
568
|
+
// filters are not part of the config-file `InlineConfig` type.
|
|
569
|
+
test, viteConfig, projectDir) {
|
|
570
|
+
// Multi-project configs resolve include/exclude per sub-project.
|
|
571
|
+
if (Array.isArray(test?.projects) || test?.workspace)
|
|
572
|
+
return true;
|
|
573
|
+
// Vitest 3 auto-loads a `vitest.workspace.*`/`vitest.projects.*` sibling file
|
|
574
|
+
// to define sub-projects even when the config object declares none; the glob
|
|
575
|
+
// resolves only the single config, so it cannot reproduce that.
|
|
576
|
+
if (vitestWorkspaceFiles.some((file) => (0, node_fs_1.existsSync)((0, node_path_1.join)(projectDir, file)))) {
|
|
577
|
+
return true;
|
|
578
|
+
}
|
|
579
|
+
// Vitest filters specs by VCS/graph state, which a glob cannot know.
|
|
580
|
+
if (test?.changed || test?.related)
|
|
581
|
+
return true;
|
|
582
|
+
// Vitest's own defaults carry none of these shapes, so only a config that
|
|
583
|
+
// spells one out reaches the runtime for this reason.
|
|
584
|
+
const configuredPatterns = [
|
|
585
|
+
test?.include,
|
|
586
|
+
test?.exclude,
|
|
587
|
+
test?.includeSource,
|
|
588
|
+
test?.typecheck?.include,
|
|
589
|
+
test?.typecheck?.exclude,
|
|
590
|
+
]
|
|
591
|
+
.filter(Array.isArray)
|
|
592
|
+
.flat();
|
|
593
|
+
if (configuredPatterns.some(patternRequiresVitestRuntime))
|
|
594
|
+
return true;
|
|
595
|
+
// Browser mode: an instance can override include/exclude/includeSource, and
|
|
596
|
+
// `dir` (the base directory Vitest scans), so a top-level glob enumerates a
|
|
597
|
+
// different spec set than the instance would. Vitest ignores `instances`
|
|
598
|
+
// while browser mode is off, and the atomized target runs `vitest run <file>`
|
|
599
|
+
// without a browser flag, so the resolved `enabled` matches the run.
|
|
600
|
+
const browserInstances = test?.browser?.instances ?? [];
|
|
601
|
+
if (test?.browser?.enabled &&
|
|
602
|
+
browserInstances.some((instance) => instance &&
|
|
603
|
+
(instance.include?.length ||
|
|
604
|
+
instance.exclude?.length ||
|
|
605
|
+
instance.includeSource?.length ||
|
|
606
|
+
instance.dir))) {
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
// A plugin can inject or reshape projects through this Vitest-only hook.
|
|
610
|
+
const plugins = viteConfig?.plugins ?? [];
|
|
611
|
+
return plugins.some((plugin) => plugin && typeof plugin === 'object' && 'configureVitest' in plugin);
|
|
612
|
+
}
|
|
613
|
+
async function getTestPathsViaVitestRuntime(fullProjectRoot, projectRoot, testDir) {
|
|
397
614
|
const { createVitest } = await import('vitest/node');
|
|
398
615
|
const vitest = await createVitest('test', {
|
|
399
616
|
root: fullProjectRoot,
|
|
400
|
-
dir
|
|
617
|
+
// `dir` defaults to `root`, and a relative `test.dir` would resolve against
|
|
618
|
+
// the working directory, which during graph creation is the workspace root
|
|
619
|
+
// rather than the project root.
|
|
620
|
+
dir: resolveTestDir(fullProjectRoot, testDir),
|
|
401
621
|
filesOnly: true,
|
|
402
622
|
watch: false,
|
|
403
623
|
});
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
export declare function loadViteDynamicImport(): Promise<
|
|
1
|
+
export declare function loadViteDynamicImport(): Promise<typeof import('vite')>;
|
|
2
2
|
export declare function loadVitestDynamicImport(): Promise<typeof import('vitest/node')>;
|
|
3
|
+
export declare function loadVitestConfigDynamicImport(): Promise<typeof import('vitest/config')>;
|
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.loadViteDynamicImport = loadViteDynamicImport;
|
|
4
4
|
exports.loadVitestDynamicImport = loadVitestDynamicImport;
|
|
5
|
-
|
|
6
|
-
// "nodenext". Vite 8 ships ESM-only type declarations (.d.mts) not resolvable
|
|
7
|
-
// under moduleResolution: "node".
|
|
5
|
+
exports.loadVitestConfigDynamicImport = loadVitestConfigDynamicImport;
|
|
8
6
|
function loadViteDynamicImport() {
|
|
9
7
|
return Function('return import("vite")')();
|
|
10
8
|
}
|
|
11
9
|
function loadVitestDynamicImport() {
|
|
12
10
|
return Function('return import("vitest/node")')();
|
|
13
11
|
}
|
|
12
|
+
function loadVitestConfigDynamicImport() {
|
|
13
|
+
return Function('return import("vitest/config")')();
|
|
14
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nx/vitest",
|
|
3
3
|
"description": "The Nx Plugin for Vitest to enable fast unit testing with Vitest.",
|
|
4
|
-
"version": "23.1.
|
|
4
|
+
"version": "23.1.1",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"files": [
|
|
7
7
|
"dist",
|
|
@@ -73,13 +73,13 @@
|
|
|
73
73
|
"tslib": "^2.3.0",
|
|
74
74
|
"semver": "^7.6.3",
|
|
75
75
|
"@phenomnomnominal/tsquery": "~6.2.0",
|
|
76
|
-
"@nx/devkit": "23.1.
|
|
77
|
-
"@nx/js": "23.1.
|
|
76
|
+
"@nx/devkit": "23.1.1",
|
|
77
|
+
"@nx/js": "23.1.1"
|
|
78
78
|
},
|
|
79
79
|
"peerDependencies": {
|
|
80
80
|
"vitest": "^3.0.0 || ^4.0.0",
|
|
81
81
|
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0",
|
|
82
|
-
"@nx/eslint": "23.1.
|
|
82
|
+
"@nx/eslint": "23.1.1"
|
|
83
83
|
},
|
|
84
84
|
"peerDependenciesMeta": {
|
|
85
85
|
"@nx/eslint": {
|
|
@@ -93,6 +93,6 @@
|
|
|
93
93
|
}
|
|
94
94
|
},
|
|
95
95
|
"devDependencies": {
|
|
96
|
-
"nx": "23.1.
|
|
96
|
+
"nx": "23.1.1"
|
|
97
97
|
}
|
|
98
98
|
}
|