Skip to content

Commit f578c08

Browse files
committed
fix(@angular/build): prevent missing NgModule scope errors in unit tests
Previously, `rootFiles` was used to restrict TypeScript compilation root names to only the test files to be executed. However, when an application `tsconfig.spec.json` includes application source files (standard for NgModule-based applications), non-standalone components rely on `AppModule` being present in the TypeScript program's root names for the Angular compiler to determine their compilation scope. Restricting root names caused template diagnostic errors such as `NG8001: '<element>' is not a known element`. This change replaces the root file allowlisting in the unit-test runner with an `excludeRootFiles` option that excludes unselected test files from the compilation roots. This ensures application files and NgModule definitions remain in the program while still ignoring unselected test files with compilation errors. Closes #34231
1 parent 23d42fc commit f578c08

8 files changed

Lines changed: 172 additions & 16 deletions

File tree

‎packages/angular/build/src/builders/application/options.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,9 @@ interface InternalOptions {
140140
disableCodeSplitting?: boolean;
141141

142142
/**
143-
* An array of files to restrict the TypeScript compilation root names to.
143+
* An array of files to exclude from the TypeScript compilation root names.
144144
*/
145-
rootFiles?: string[];
145+
excludeRootFiles?: string[];
146146
}
147147

148148
/** Full set of options for `application` builder. */
@@ -456,7 +456,7 @@ export async function normalizeOptions(
456456
verbose,
457457
watch,
458458
progress = true,
459-
rootFiles,
459+
excludeRootFiles,
460460
externalPackages,
461461
namedChunks,
462462
budgets,
@@ -504,7 +504,7 @@ export async function normalizeOptions(
504504
workspaceRoot,
505505
entryPoints,
506506
disableCodeSplitting,
507-
rootFiles: rootFiles?.map((file: string) => path.resolve(workspaceRoot, file)),
507+
excludeRootFiles: excludeRootFiles?.map((file: string) => path.resolve(workspaceRoot, file)),
508508
optimizationOptions,
509509
outputOptions,
510510
outExtension,

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

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ import { type NormalizedUnitTestBuilderOptions, injectTestingPolyfills } from '.
2121
import { findTests, getTestEntrypoints } from '../../test-discovery';
2222
import { RunnerOptions } from '../api';
2323

24+
const DEFAULT_TEST_PATTERNS = ['**/*.spec.ts', '**/*.test.ts'];
25+
2426
/**
2527
* Creates the virtual file contents to initialize the Angular testing environment (TestBed).
2628
*
@@ -210,14 +212,7 @@ export async function getVitestBuildOptions(
210212
removeTestExtension: true,
211213
});
212214

213-
const rootFiles = [...testFiles];
214-
if (providersFile) {
215-
rootFiles.push(providersFile);
216-
}
217-
218215
if (setupFiles?.length) {
219-
rootFiles.push(...setupFiles);
220-
221216
const setupEntryPoints = getTestEntrypoints(setupFiles, {
222217
projectSourceRoot,
223218
workspaceRoot,
@@ -230,6 +225,21 @@ export async function getVitestBuildOptions(
230225
}
231226
}
232227

228+
const allTestFiles = await findTests(DEFAULT_TEST_PATTERNS, [], workspaceRoot, projectSourceRoot);
229+
const testFilesSet = new Set(testFiles);
230+
if (providersFile) {
231+
testFilesSet.add(toPosixPath(providersFile));
232+
}
233+
234+
if (setupFiles?.length) {
235+
for (const setupFile of setupFiles) {
236+
testFilesSet.add(toPosixPath(setupFile));
237+
}
238+
}
239+
240+
const unselectedTestFiles = allTestFiles.filter((file) => !testFilesSet.has(file));
241+
const excludeRootFiles = unselectedTestFiles.length > 0 ? unselectedTestFiles : undefined;
242+
233243
// The Angular compiler facade must be loaded in a dedicated setup file before TestBed initialization.
234244
// This ensures the compiler facade is published before 'init-testbed' or any shared code-split chunks
235245
// (such as those from a configured 'providersFile') are evaluated.
@@ -267,7 +277,7 @@ export async function getVitestBuildOptions(
267277
optimization: false,
268278
namedChunks: false,
269279
entryPoints,
270-
rootFiles,
280+
excludeRootFiles,
271281
// Vitest's Node-based module loading emulation (vite-node) is not fully spec compliant and lacks
272282
// live ESM bindings across chunk boundaries. This can cause uninitialized exports or break mocking.
273283
// Disabling code splitting avoids shared chunks, but increases build and coverage memory/time.

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

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,5 +110,77 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => {
110110
const { result } = await harness.executeOnce();
111111
expect(result?.success).toBeTrue();
112112
});
113+
114+
it('should compile NgModule declared components when using include in an NgModule app', async () => {
115+
await harness.writeFiles({
116+
'src/tsconfig.spec.json': JSON.stringify({
117+
extends: '../tsconfig.json',
118+
compilerOptions: {
119+
outDir: '../out-tsc/spec',
120+
types: ['vitest/globals'],
121+
},
122+
include: ['**/*.d.ts', '**/*.ts'],
123+
}),
124+
'src/app/app.module.ts': `
125+
import { NgModule } from '@angular/core';
126+
import { BrowserModule } from '@angular/platform-browser';
127+
import { RouterModule } from '@angular/router';
128+
import { AppComponent } from './app.component';
129+
130+
@NgModule({
131+
declarations: [AppComponent],
132+
imports: [BrowserModule, RouterModule],
133+
})
134+
export class AppModule {}
135+
`,
136+
'src/app/app.component.ts': `
137+
import { Component } from '@angular/core';
138+
139+
@Component({
140+
selector: 'app-root',
141+
standalone: false,
142+
templateUrl: './app.component.html',
143+
})
144+
export class AppComponent {}
145+
`,
146+
'src/app/app.component.html': '<router-outlet />',
147+
'src/app/app.component.spec.ts': `
148+
import { TestBed } from '@angular/core/testing';
149+
import { RouterModule } from '@angular/router';
150+
import { AppComponent } from './app.component';
151+
152+
describe('AppComponent', () => {
153+
beforeEach(async () => {
154+
await TestBed.configureTestingModule({
155+
imports: [RouterModule.forRoot([])],
156+
declarations: [AppComponent],
157+
}).compileComponents();
158+
});
159+
160+
it('should create the app', () => {
161+
const fixture = TestBed.createComponent(AppComponent);
162+
const app = fixture.componentInstance;
163+
expect(app).toBeTruthy();
164+
});
165+
});
166+
`,
167+
'src/app/broken.service.spec.ts': `
168+
// This test has a TypeScript type error that would fail compilation if compiled
169+
const invalidNumber: number = 'not a number';
170+
describe('BrokenService', () => {
171+
it('should fail compilation', () => {
172+
expect(invalidNumber).toBe(1);
173+
});
174+
});`,
175+
});
176+
177+
harness.useTarget('test', {
178+
...BASE_OPTIONS,
179+
include: ['src/app/app.component.spec.ts'],
180+
});
181+
182+
const { result } = await harness.executeOnce();
183+
expect(result?.success).toBeTrue();
184+
});
113185
});
114186
});

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

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,68 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => {
5555
expect(result?.success).toBeFalse();
5656
expectLog(logs, `The specified tsConfig file 'random/tsconfig.spec.json' does not exist.`);
5757
});
58+
59+
it('should compile NgModule declared components when tsConfig includes application files', async () => {
60+
await harness.writeFiles({
61+
'src/tsconfig.spec.json': JSON.stringify({
62+
extends: '../tsconfig.json',
63+
compilerOptions: {
64+
outDir: '../out-tsc/spec',
65+
types: ['vitest/globals'],
66+
},
67+
include: ['**/*.d.ts', '**/*.ts'],
68+
}),
69+
'src/app/app.module.ts': `
70+
import { NgModule } from '@angular/core';
71+
import { BrowserModule } from '@angular/platform-browser';
72+
import { RouterModule } from '@angular/router';
73+
import { AppComponent } from './app.component';
74+
75+
@NgModule({
76+
declarations: [AppComponent],
77+
imports: [BrowserModule, RouterModule],
78+
})
79+
export class AppModule {}
80+
`,
81+
'src/app/app.component.ts': `
82+
import { Component } from '@angular/core';
83+
84+
@Component({
85+
selector: 'app-root',
86+
standalone: false,
87+
templateUrl: './app.component.html',
88+
})
89+
export class AppComponent {}
90+
`,
91+
'src/app/app.component.html': '<router-outlet />',
92+
'src/app/app.component.spec.ts': `
93+
import { TestBed } from '@angular/core/testing';
94+
import { RouterModule } from '@angular/router';
95+
import { AppComponent } from './app.component';
96+
97+
describe('AppComponent', () => {
98+
beforeEach(async () => {
99+
await TestBed.configureTestingModule({
100+
imports: [RouterModule.forRoot([])],
101+
declarations: [AppComponent],
102+
}).compileComponents();
103+
});
104+
105+
it('should create the app', () => {
106+
const fixture = TestBed.createComponent(AppComponent);
107+
const app = fixture.componentInstance;
108+
expect(app).toBeTruthy();
109+
});
110+
});
111+
`,
112+
});
113+
114+
harness.useTarget('test', {
115+
...BASE_OPTIONS,
116+
});
117+
118+
const { result } = await harness.executeOnce();
119+
expect(result?.success).toBeTrue();
120+
});
58121
});
59122
});

‎packages/angular/build/src/tools/angular/compilation/compiler-options.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export interface CompilerOptionOverrides {
2121
includeTestMetadata?: boolean;
2222
customConditions?: string[];
2323
rootFiles?: string[];
24+
excludeRootFiles?: string[];
2425
declarationMap?: boolean;
2526
compilationMode?: 'full' | 'partial';
2627
paths?: Record<string, string[]>;

‎packages/angular/build/src/tools/angular/compilation/typescript-compilation.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,24 @@ export abstract class TypeScriptCompilation extends AngularCompilation {
6666
const rootFilesSet = new Set(
6767
compilerOptionOverrides.rootFiles.map((file) => canonicalizePath(toPosixPath(file))),
6868
);
69+
6970
for (const file of originalRootNames) {
7071
if (/\.d\.[cm]?ts$/i.test(file)) {
7172
rootFilesSet.add(canonicalizePath(toPosixPath(file)));
7273
}
7374
}
75+
7476
rootNames = [...rootFilesSet];
7577
}
7678

79+
if (compilerOptionOverrides?.excludeRootFiles?.length) {
80+
const excludeSet = new Set(
81+
compilerOptionOverrides.excludeRootFiles.map((file) => canonicalizePath(toPosixPath(file))),
82+
);
83+
84+
rootNames = rootNames.filter((file) => !excludeSet.has(canonicalizePath(toPosixPath(file))));
85+
}
86+
7787
const { compilerOptions, warnings } = transformCompilerOptions(
7888
ts,
7989
originalCompilerOptions,

‎packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ export interface CompilerPluginOptions {
6161
externalRuntimeStyles?: boolean;
6262
instrumentForCoverage?: (request: string) => boolean;
6363
templateUpdates?: Map<string, string>;
64-
rootFiles?: string[];
64+
excludeRootFiles?: string[];
6565
}
6666

6767
// eslint-disable-next-line max-lines-per-function
@@ -330,7 +330,7 @@ export function createCompilerPlugin(
330330
instrumentForCoverage: !!pluginOptions.instrumentForCoverage,
331331
includeTestMetadata: !!pluginOptions.includeTestMetadata,
332332
customConditions: build.initialOptions.conditions,
333-
rootFiles: pluginOptions.rootFiles,
333+
excludeRootFiles: pluginOptions.excludeRootFiles,
334334
},
335335
);
336336

‎packages/angular/build/src/tools/esbuild/compiler-plugin-options.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export function createCompilerPluginOptions(
2828
externalRuntimeStyles,
2929
instrumentForCoverage,
3030
optimizationOptions,
31-
rootFiles,
31+
excludeRootFiles,
3232
} = options;
3333
const incremental = !!options.watch;
3434

@@ -46,6 +46,6 @@ export function createCompilerPluginOptions(
4646
instrumentForCoverage,
4747
templateUpdates,
4848
includeTestMetadata: !optimizationOptions.scripts,
49-
rootFiles,
49+
excludeRootFiles,
5050
};
5151
}

0 commit comments

Comments
 (0)