Skip to content

Commit 89e9d60

Browse files
committed
fix(@angular/build): execute setup file hooks for each spec file when coverage is enabled
When code coverage is enabled with the Vitest runner, test entry points are served as a virtual one-line import stub (`import "./${outputPath}";`) so that the test files themselves can be excluded from coverage reports after sourcemap remapping. However, setup files configured via `setupFiles` were also treated as test entry points and served as virtual stubs. Because Vitest only invalidates the top-level setup module between spec files, the imported intermediate bundle was cached in `vite-node` after its initial evaluation and never re-evaluated on subsequent spec files. This caused setup file hooks (e.g. `beforeEach` / `afterEach`) to silently only run for the first spec file of each worker. This commit excludes setup files from being wrapped in the virtual coverage stub, allowing them to be directly evaluated and re-evaluated by Vitest before each spec file. Fixes #34137
1 parent 69acf5b commit 89e9d60

3 files changed

Lines changed: 77 additions & 2 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,7 @@ export class VitestExecutor implements TestExecutor {
333333
projectName,
334334
buildResultFiles: this.buildResultFiles,
335335
testFileToEntryPoint: this.testFileToEntryPoint,
336+
setupFiles: testSetupFiles,
336337
});
337338

338339
const debugOptions = debug

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ interface PluginOptions {
3737
projectName: string;
3838
buildResultFiles: ReadonlyMap<string, ResultFile>;
3939
testFileToEntryPoint: ReadonlyMap<string, string>;
40+
setupFiles: readonly string[];
4041
}
4142

4243
type VitestCoverageOption = Exclude<InlineConfig['coverage'], undefined>;
@@ -313,8 +314,13 @@ async function loadResultFile(file: ResultFile): Promise<string> {
313314
}
314315

315316
export function createVitestPlugins(pluginOptions: PluginOptions): Vite.Plugin[] {
316-
const { workspaceRoot, buildResultFiles, testFileToEntryPoint } = pluginOptions;
317+
const { workspaceRoot, buildResultFiles, testFileToEntryPoint, setupFiles } = pluginOptions;
317318
const isWindows = platform() === 'win32';
319+
const setupFileSet = new Set(
320+
setupFiles.map((file) =>
321+
toPosixPath(path.isAbsolute(file) ? file : path.join(workspaceRoot, file)),
322+
),
323+
);
318324
let vitestConfig: ResolvedConfig;
319325

320326
return [
@@ -387,7 +393,11 @@ export function createVitestPlugins(pluginOptions: PluginOptions): Vite.Plugin[]
387393
if (entryPoint) {
388394
outputPath = entryPoint + '.js';
389395

390-
if (vitestConfig?.coverage?.enabled) {
396+
// Setup files must not be wrapped in a virtual import stub because Vitest only invalidates
397+
// the setup file itself between test files; wrapping it would cause the underlying bundle
398+
// to be cached, preventing per-test hooks from running on subsequent test files.
399+
const isSetupFile = setupFileSet.has(id);
400+
if (vitestConfig?.coverage?.enabled && !isSetupFile) {
391401
// To support coverage exclusion of the actual test file, the virtual
392402
// test entry point only references the built and bundled intermediate file.
393403
// If vitest supported an "excludeOnlyAfterRemap" option, this could be removed completely.

‎packages/angular/build/src/builders/unit-test/tests/options/setup-files_spec.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,69 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => {
5454
const { result } = await harness.executeOnce();
5555
expect(result?.success).toBeTrue();
5656
});
57+
58+
it('should run setup file hooks for each spec file when coverage is enabled', async () => {
59+
harness.writeFile(
60+
'vitest.config.mts',
61+
`
62+
import { defineConfig } from 'vitest/config';
63+
64+
export default defineConfig({
65+
test: {
66+
fileParallelism: false,
67+
},
68+
});
69+
`,
70+
);
71+
72+
await harness.writeFiles({
73+
'src/setup.ts': `
74+
import { afterEach, beforeEach, expect } from 'vitest';
75+
const global = globalThis as typeof globalThis & {
76+
seenBeforeEach?: Set<string>;
77+
seenAfterEach?: Set<string>;
78+
};
79+
const seenBeforeEach = (global.seenBeforeEach ??= new Set<string>());
80+
const seenAfterEach = (global.seenAfterEach ??= new Set<string>());
81+
beforeEach(() => {
82+
const file = (expect.getState().testPath ?? '').split(/[/\\]/).pop() ?? '';
83+
seenBeforeEach.add(file);
84+
});
85+
afterEach(() => {
86+
const file = (expect.getState().testPath ?? '').split(/[/\\]/).pop() ?? '';
87+
seenAfterEach.add(file);
88+
});
89+
`,
90+
'src/app/app.component.spec.ts': `
91+
import { expect, it } from 'vitest';
92+
it('has beforeEach hook run from setup file', () => {
93+
const global = globalThis as typeof globalThis & { seenBeforeEach?: Set<string> };
94+
expect(global.seenBeforeEach?.has('app.component.spec.ts')).toBe(true);
95+
});
96+
`,
97+
'src/app/second.spec.ts': `
98+
import { expect, it } from 'vitest';
99+
it('has hooks run from setup file on second spec file', () => {
100+
const global = globalThis as typeof globalThis & {
101+
seenBeforeEach?: Set<string>;
102+
seenAfterEach?: Set<string>;
103+
};
104+
expect(global.seenBeforeEach?.has('second.spec.ts')).toBe(true);
105+
// Verify afterEach ran for the previous spec file
106+
expect(global.seenAfterEach?.has('app.component.spec.ts')).toBe(true);
107+
});
108+
`,
109+
});
110+
111+
harness.useTarget('test', {
112+
...BASE_OPTIONS,
113+
coverage: true,
114+
runnerConfig: 'vitest.config.mts',
115+
setupFiles: ['src/setup.ts'],
116+
});
117+
118+
const { result } = await harness.executeOnce();
119+
expect(result?.success).toBeTrue();
120+
});
57121
});
58122
});

0 commit comments

Comments
 (0)