Skip to content

Commit 4d3926d

Browse files
committed
fix(@angular/build): rebase Vitest incremental paths when workspace root is aliased
When `vitestConfig.root` differs from `workspaceRoot` (such as with symlinks or Windows `subst` drives), `VitestExecutor` still invalidated and queried test specifications during incremental watch-mode rebuilds using the un-rebased `workspaceRoot` paths. Because Vitest keys its module graph and test specifications against `vitest.config.root`, incremental re-runs could fail to invalidate cached modules or locate the affected test specifications. To address this, extract a `rebasePath` helper in `plugins.ts` that converts paths between roots while leaving paths that cannot be expressed relative to the original root (such as files on a different Windows drive) unchanged instead of concatenating them. `VitestExecutor` now uses this helper during incremental rebuilds to rebase modified output and source file paths onto `vitest.config.root` when the root is aliased. Additionally, `configureVitest` now rebases from the original plugin options rather than mutating from the previous root so repeated invocations remain idempotent. `plugins_spec.ts` is expanded to cover `rebasePath`, `angular:` virtual entries, absolute setup files under coverage, and repeated `configureVitest` calls, and a new `executor_spec.ts` covers the incremental rebuild paths.
1 parent 8b26efa commit 4d3926d

5 files changed

Lines changed: 282 additions & 21 deletions

File tree

‎packages/angular/build/BUILD.bazel‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ ts_project(
155155
":node_modules/@babel/core",
156156
":node_modules/@parcel/watcher",
157157
":node_modules/oxc-parser",
158+
":node_modules/vitest",
158159
"//:node_modules/@angular/compiler-cli",
159160
"//:node_modules/@angular/router",
160161
"//:node_modules/@types/jasmine",

‎packages/angular/build/src/builders/unit-test/runners/vitest/executor.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import { NormalizedUnitTestBuilderOptions } from '../../options';
3030
import type { TestExecutor } from '../api';
3131
import { setupBrowserConfiguration } from './browser-provider';
3232
import { findVitestBaseConfig } from './configuration';
33-
import { createVitestConfigPlugin, createVitestPlugins } from './plugins';
33+
import { createVitestConfigPlugin, createVitestPlugins, rebasePath } from './plugins';
3434

3535
enum DebugLogLevel {
3636
Info = 1,
@@ -144,6 +144,11 @@ export class VitestExecutor implements TestExecutor {
144144

145145
let testResults;
146146
if (buildResult.kind === ResultKind.Incremental) {
147+
const vitestRoot = vitest.config.root;
148+
const workspaceRoot = this.options.workspaceRoot;
149+
const isAliasedRoot = Boolean(vitestRoot && vitestRoot !== toPosixPath(workspaceRoot));
150+
const activeRoot = isAliasedRoot ? vitestRoot : workspaceRoot;
151+
147152
// To rerun tests, Vitest needs the original test file paths, not the output paths.
148153
const modifiedSourceFiles = new Set<string>();
149154
for (const modifiedFile of [...buildResult.modified, ...buildResult.added]) {
@@ -162,15 +167,14 @@ export class VitestExecutor implements TestExecutor {
162167
`Could not map output file '${modifiedFile}' to a source file. It may not be a test file.`,
163168
);
164169
}
165-
vitest.invalidateFile(
166-
this.normalizePath(path.join(this.options.workspaceRoot, modifiedFile)),
167-
);
170+
vitest.invalidateFile(this.normalizePath(path.join(activeRoot, modifiedFile)));
168171
}
169172

170173
const specsToRerun = [];
171174
for (const file of modifiedSourceFiles) {
172-
vitest.invalidateFile(file);
173-
const specs = vitest.getModuleSpecifications(file);
175+
const targetFile = isAliasedRoot ? rebasePath(file, workspaceRoot, vitestRoot) : file;
176+
vitest.invalidateFile(targetFile);
177+
const specs = vitest.getModuleSpecifications(targetFile);
174178
if (specs) {
175179
specsToRerun.push(...specs);
176180
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import type { BuilderContext } from '@angular-devkit/architect';
10+
import path from 'node:path';
11+
import type { Vitest } from 'vitest/node';
12+
import { toPosixPath } from '../../../../utils/path';
13+
import { type IncrementalResult, ResultKind } from '../../../application/results';
14+
import type { NormalizedUnitTestBuilderOptions } from '../../options';
15+
import { VitestExecutor } from './executor';
16+
17+
describe('VitestExecutor', () => {
18+
describe('incremental rebuilds', () => {
19+
const workspaceRoot = path.resolve('/logical-workspace/test-project');
20+
const specFile = toPosixPath(path.join(workspaceRoot, 'src/app/app.spec.ts'));
21+
const incrementalResult: IncrementalResult = {
22+
kind: ResultKind.Incremental,
23+
added: [],
24+
removed: [],
25+
modified: ['spec-src-app-app-spec.js', 'chunk-ABCDEF.js'],
26+
files: [],
27+
};
28+
29+
let originalExitCode: typeof process.exitCode;
30+
31+
beforeEach(() => {
32+
// The executor resets the process exit code when executing.
33+
originalExitCode = process.exitCode;
34+
});
35+
36+
afterEach(() => {
37+
process.exitCode = originalExitCode;
38+
});
39+
40+
/**
41+
* Executes an incremental rebuild with a stand-in Vitest instance that uses the provided root.
42+
* The stand-in only has test specifications for the module ids in `knownModuleIds`.
43+
*/
44+
async function executeIncremental(vitestRoot: string, knownModuleIds: string[]) {
45+
const executor = new VitestExecutor(
46+
'test-project',
47+
{ workspaceRoot } as NormalizedUnitTestBuilderOptions,
48+
new Map([['spec-src-app-app-spec', specFile]]),
49+
{ info: () => {} } as unknown as BuilderContext['logger'],
50+
);
51+
52+
const invalidateFile = jasmine.createSpy('invalidateFile');
53+
const getModuleSpecifications = jasmine
54+
.createSpy('getModuleSpecifications')
55+
.and.callFake((moduleId: string) =>
56+
knownModuleIds.includes(moduleId) ? [{ moduleId }] : [],
57+
);
58+
const rerunTestSpecifications = jasmine
59+
.createSpy('rerunTestSpecifications')
60+
.and.resolveTo({ testModules: [{ ok: () => true }] });
61+
62+
// Provide an already initialized Vitest instance to avoid starting Vitest.
63+
executor['vitest'] = {
64+
config: { root: vitestRoot },
65+
state: { getTestModules: () => [] },
66+
invalidateFile,
67+
getModuleSpecifications,
68+
rerunTestSpecifications,
69+
} as unknown as Vitest;
70+
71+
const outputs = [];
72+
for await (const output of executor.execute(incrementalResult)) {
73+
outputs.push(output);
74+
}
75+
76+
return { outputs, invalidateFile, getModuleSpecifications, rerunTestSpecifications };
77+
}
78+
79+
it('uses workspace root based paths when the Vitest root is not aliased', async () => {
80+
const root = toPosixPath(workspaceRoot);
81+
const { outputs, invalidateFile, getModuleSpecifications, rerunTestSpecifications } =
82+
await executeIncremental(root, [specFile]);
83+
84+
expect(invalidateFile.calls.allArgs()).toEqual([
85+
[`${root}/spec-src-app-app-spec.js`],
86+
[`${root}/chunk-ABCDEF.js`],
87+
[specFile],
88+
]);
89+
expect(getModuleSpecifications.calls.allArgs()).toEqual([[specFile]]);
90+
expect(rerunTestSpecifications).toHaveBeenCalledOnceWith([{ moduleId: specFile }]);
91+
expect(outputs).toEqual([{ success: true }]);
92+
});
93+
94+
it('rebases paths onto the Vitest root when the root is aliased', async () => {
95+
const physicalRoot = toPosixPath(path.resolve('/physical-disk/tmp/test-project'));
96+
const physicalSpecFile = `${physicalRoot}/src/app/app.spec.ts`;
97+
const { outputs, invalidateFile, getModuleSpecifications, rerunTestSpecifications } =
98+
await executeIncremental(physicalRoot, [physicalSpecFile]);
99+
100+
expect(invalidateFile.calls.allArgs()).toEqual([
101+
[`${physicalRoot}/spec-src-app-app-spec.js`],
102+
[`${physicalRoot}/chunk-ABCDEF.js`],
103+
[physicalSpecFile],
104+
]);
105+
expect(getModuleSpecifications.calls.allArgs()).toEqual([[physicalSpecFile]]);
106+
expect(rerunTestSpecifications).toHaveBeenCalledOnceWith([{ moduleId: physicalSpecFile }]);
107+
expect(outputs).toEqual([{ success: true }]);
108+
});
109+
});
110+
});

‎packages/angular/build/src/builders/unit-test/runners/vitest/plugins.ts‎

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import assert from 'node:assert';
1010
import { readFile } from 'node:fs/promises';
1111
import { platform } from 'node:os';
12-
import path from 'node:path';
12+
import path, { type PlatformPath } from 'node:path';
1313
import type {
1414
BrowserConfigOptions,
1515
InlineConfig,
@@ -338,6 +338,33 @@ async function loadResultFile(file: ResultFile): Promise<string> {
338338
return readFile(file.source, 'utf-8');
339339
}
340340

341+
/**
342+
* Rebases a file path from `fromRoot` to `toRoot` in POSIX format.
343+
*
344+
* The path is rebased using its location relative to `fromRoot`. This includes a path outside of
345+
* `fromRoot` (reached through `..` segments), which matches how Vitest resolves the root relative
346+
* test `include` entries. Only a path that cannot be expressed relative to `fromRoot`, such as a
347+
* file on a different Windows drive, is left unchanged (as POSIX).
348+
*
349+
* @param filePath The absolute file path to rebase.
350+
* @param fromRoot The root that `filePath` is currently based on.
351+
* @param toRoot The root to rebase `filePath` onto.
352+
* @param pathImpl The path implementation to use. Defaults to that of the host platform.
353+
* @returns The rebased file path in POSIX format.
354+
*/
355+
export function rebasePath(
356+
filePath: string,
357+
fromRoot: string,
358+
toRoot: string,
359+
pathImpl: PlatformPath = path,
360+
): string {
361+
const relative = pathImpl.relative(fromRoot, filePath);
362+
const rebased = pathImpl.isAbsolute(relative) ? filePath : pathImpl.join(toRoot, relative);
363+
364+
// Equivalent to `toPosixPath` but follows `pathImpl` instead of the host platform.
365+
return pathImpl.sep === '\\' ? rebased.replace(/\\/g, '/') : rebased;
366+
}
367+
341368
export function createVitestPlugins(pluginOptions: PluginOptions): Vite.Plugin[] {
342369
const { buildResultFiles, setupFiles } = pluginOptions;
343370
let { workspaceRoot, testFileToEntryPoint } = pluginOptions;
@@ -370,24 +397,19 @@ export function createVitestPlugins(pluginOptions: PluginOptions): Vite.Plugin[]
370397
vitestConfig = context.vitest.config;
371398

372399
if (vitestConfig.root && vitestConfig.root !== toPosixPath(workspaceRoot)) {
373-
const previousRoot = workspaceRoot;
400+
const originalRoot = pluginOptions.workspaceRoot;
374401
workspaceRoot = vitestConfig.root;
375402
testFileToEntryPoint = new Map(
376-
Array.from(testFileToEntryPoint, ([file, entryPoint]) => [
377-
file.startsWith('angular:')
378-
? file
379-
: toPosixPath(path.join(workspaceRoot, path.relative(previousRoot, file))),
403+
Array.from(pluginOptions.testFileToEntryPoint, ([file, entryPoint]) => [
404+
file.startsWith('angular:') ? file : rebasePath(file, originalRoot, workspaceRoot),
380405
entryPoint,
381406
]),
382407
);
383408
setupFileSet = new Set(
384409
setupFiles.map((file) =>
385-
toPosixPath(
386-
path.join(
387-
workspaceRoot,
388-
path.isAbsolute(file) ? path.relative(previousRoot, file) : file,
389-
),
390-
),
410+
path.isAbsolute(file)
411+
? rebasePath(file, originalRoot, workspaceRoot)
412+
: toPosixPath(path.join(workspaceRoot, file)),
391413
),
392414
);
393415
}

‎packages/angular/build/src/builders/unit-test/runners/vitest/plugins_spec.ts‎

Lines changed: 127 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,45 @@ import path from 'node:path';
1010
import { BuildOutputFileType } from '../../../../tools/esbuild/bundler-files';
1111
import { toPosixPath } from '../../../../utils/path';
1212
import type { ResultFile } from '../../../application/results';
13-
import { createVitestPlugins } from './plugins';
13+
import { createVitestPlugins, rebasePath } from './plugins';
14+
15+
describe('rebasePath', () => {
16+
it('rebases a path from fromRoot to toRoot in POSIX format', () => {
17+
const fromRoot = path.resolve('/logical-workspace/test-project');
18+
const toRoot = toPosixPath(path.resolve('/physical-disk/tmp/test-project'));
19+
const filePath = path.join(fromRoot, 'src/app/app.spec.ts');
20+
21+
expect(rebasePath(filePath, fromRoot, toRoot)).toBe(`${toRoot}/src/app/app.spec.ts`);
22+
});
23+
24+
it('rebases a path outside of fromRoot using its relative location', () => {
25+
expect(
26+
rebasePath(
27+
'/logical/shared/setup.ts',
28+
'/logical/test-project',
29+
'/physical/test-project',
30+
path.posix,
31+
),
32+
).toBe('/physical/shared/setup.ts');
33+
});
34+
35+
it('rebases a Windows path onto a different drive in POSIX format', () => {
36+
expect(
37+
rebasePath(
38+
'X:\\test-project\\src\\app\\app.spec.ts',
39+
'X:\\test-project',
40+
'D:/tmp/test-project',
41+
path.win32,
42+
),
43+
).toBe('D:/tmp/test-project/src/app/app.spec.ts');
44+
});
45+
46+
it('leaves a path on a different Windows drive than fromRoot unchanged', () => {
47+
expect(
48+
rebasePath('C:\\shared\\setup.ts', 'X:\\test-project', 'D:/tmp/test-project', path.win32),
49+
).toBe('C:/shared/setup.ts');
50+
});
51+
});
1452

1553
describe('createVitestPlugins', () => {
1654
it('resolves and loads setup and spec files when vitestConfig.root differs from workspaceRoot', async () => {
@@ -41,7 +79,10 @@ describe('createVitestPlugins', () => {
4179
],
4280
]);
4381

44-
const testFileToEntryPoint = new Map<string, string>([[specFile, 'spec-src-app-app-spec']]);
82+
const testFileToEntryPoint = new Map<string, string>([
83+
[specFile, 'spec-src-app-app-spec'],
84+
['angular:compiler-init', 'init-compiler'],
85+
]);
4586

4687
const plugins = createVitestPlugins({
4788
workspaceRoot,
@@ -56,7 +97,10 @@ describe('createVitestPlugins', () => {
5697
expect(inMemoryPlugin).toBeDefined();
5798

5899
const configureVitest = inMemoryPlugin?.configureVitest as
59-
((context: { vitest: { config: { root: string } } }) => void) | undefined;
100+
| ((context: {
101+
vitest: { config: { root: string; coverage?: { enabled: boolean } } };
102+
}) => void)
103+
| undefined;
60104
configureVitest?.({
61105
vitest: {
62106
config: {
@@ -73,6 +117,8 @@ describe('createVitestPlugins', () => {
73117
id: string,
74118
) => Promise<{ code: string; map?: unknown } | undefined>;
75119

120+
expect(resolveId('angular:compiler-init', undefined)).toBe('angular:compiler-init');
121+
76122
const expectedSetupId = `${physicalRoot}/init-compiler.js`;
77123
const resolvedSetupId = resolveId(expectedSetupId, undefined);
78124
expect(resolvedSetupId).toBe(expectedSetupId);
@@ -87,4 +133,82 @@ describe('createVitestPlugins', () => {
87133
const loadedSpec = await load(expectedSpecId);
88134
expect(loadedSpec?.code).toBe('console.log("spec");');
89135
});
136+
137+
it('rebases absolute setupFiles for coverage exclusion and handles repeated configureVitest calls', async () => {
138+
const workspaceRoot = path.resolve('/logical-workspace/test-project');
139+
const firstPhysicalRoot = toPosixPath(path.resolve('/physical-disk/first/test-project'));
140+
const secondPhysicalRoot = toPosixPath(path.resolve('/physical-disk/second/test-project'));
141+
const userSetupFile = toPosixPath(path.join(workspaceRoot, 'src/test-setup.ts'));
142+
const specFile = toPosixPath(path.join(workspaceRoot, 'src/app/app.spec.ts'));
143+
144+
const buildResultFiles = new Map<string, ResultFile>([
145+
[
146+
'setup-src-test-setup.js',
147+
{
148+
origin: 'memory',
149+
path: 'setup-src-test-setup.js',
150+
type: BuildOutputFileType.Root,
151+
contents: new TextEncoder().encode('console.log("user-setup");'),
152+
hash: 'hash-user-setup',
153+
},
154+
],
155+
[
156+
'spec-src-app-app-spec.js',
157+
{
158+
origin: 'memory',
159+
path: 'spec-src-app-app-spec.js',
160+
type: BuildOutputFileType.Root,
161+
contents: new TextEncoder().encode('console.log("spec");'),
162+
hash: 'hash-spec',
163+
},
164+
],
165+
]);
166+
167+
const testFileToEntryPoint = new Map<string, string>([
168+
[userSetupFile, 'setup-src-test-setup'],
169+
[specFile, 'spec-src-app-app-spec'],
170+
]);
171+
172+
const plugins = createVitestPlugins({
173+
workspaceRoot,
174+
projectSourceRoot: path.join(workspaceRoot, 'src'),
175+
projectName: 'test-project',
176+
buildResultFiles,
177+
testFileToEntryPoint,
178+
setupFiles: [userSetupFile],
179+
});
180+
181+
const inMemoryPlugin = plugins.find((p) => p.name === 'angular:test-in-memory-provider');
182+
const configureVitest = inMemoryPlugin?.configureVitest as
183+
| ((context: {
184+
vitest: { config: { root: string; coverage?: { enabled: boolean } } };
185+
}) => void)
186+
| undefined;
187+
const load = inMemoryPlugin?.load as (
188+
id: string,
189+
) => Promise<{ code: string; map?: unknown } | undefined>;
190+
191+
configureVitest?.({
192+
vitest: {
193+
config: {
194+
root: firstPhysicalRoot,
195+
coverage: { enabled: true },
196+
},
197+
},
198+
});
199+
configureVitest?.({
200+
vitest: {
201+
config: {
202+
root: secondPhysicalRoot,
203+
coverage: { enabled: true },
204+
},
205+
},
206+
});
207+
208+
const loadedSetup = await load(`${secondPhysicalRoot}/src/test-setup.ts`);
209+
expect(loadedSetup?.code).toBe('console.log("user-setup");');
210+
211+
const loadedSpec = await load(`${secondPhysicalRoot}/src/app/app.spec.ts`);
212+
expect(loadedSpec?.code).toBe('import "./spec-src-app-app-spec.js";');
213+
});
90214
});

0 commit comments

Comments
 (0)