Skip to content

Commit d277ee9

Browse files
fix(@angular/build): preserve component initialization in Karma test bundles
Load selected Karma specs through a shared virtual module while retaining spec entry names and shared framework chunks. Add a browser regression for barrel imports combined with async specs. Fixes #34250
1 parent 2c6e8b9 commit d277ee9

2 files changed

Lines changed: 117 additions & 1 deletion

File tree

‎packages/angular/build/src/builders/karma/application_builder.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import type { KarmaBuilderTransformsOptions } from './index';
3939
interface BuildOptions extends ApplicationBuilderInternalOptions {
4040
// We know that it's always a string since we set it.
4141
outputPath: string;
42+
entryPoints: Map<string, string>;
4243
}
4344

4445
class ApplicationBuildError extends Error {
@@ -213,6 +214,25 @@ async function runEsbuild(
213214
context: BuilderContext,
214215
projectSourceRoot: string,
215216
): Promise<[Result & { kind: ResultKind.Full }, AsyncIterator<Result> | null]> {
217+
// Keep specs in a single module graph so cross-chunk lazy initialization cannot
218+
// expose an uninitialized barrel export. Preserve entry names and shared framework chunks.
219+
const specFiles: string[] = [];
220+
const entryPoints = buildOptions.entryPoints;
221+
for (const [name, file] of entryPoints) {
222+
if (name.startsWith('spec-')) {
223+
specFiles.push(file);
224+
entryPoints.set(name, 'angular:karma-specs');
225+
}
226+
}
227+
buildOptions.rootFiles = specFiles;
228+
const virtualSpecs = createVirtualModulePlugin({
229+
namespace: 'angular:karma-specs',
230+
loadContent: () => ({
231+
contents: specFiles.map((file) => `import ${JSON.stringify(file)};`).join('\n'),
232+
loader: 'js',
233+
resolveDir: projectSourceRoot,
234+
}),
235+
});
216236
const usesZoneJS = buildOptions.polyfills?.includes('zone.js');
217237
let hasLocalize = false;
218238
try {
@@ -248,7 +268,9 @@ async function runEsbuild(
248268

249269
// Build tests with `application` builder, using test files as entry points.
250270
const [buildOutput, buildIterator] = await first(
251-
buildApplicationInternal(buildOptions, context, { codePlugins: [virtualTestBedInit] }),
271+
buildApplicationInternal(buildOptions, context, {
272+
codePlugins: [virtualTestBedInit, virtualSpecs],
273+
}),
252274
{ cancel: !buildOptions.watch },
253275
);
254276
if (buildOutput.kind === ResultKind.Failure) {
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
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 { execute } from '../../index';
10+
import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup';
11+
12+
describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => {
13+
describe('Behavior: barrel imports with async tests', () => {
14+
beforeEach(async () => {
15+
await setupTarget(harness);
16+
});
17+
it('should initialize components imported through a barrel', async () => {
18+
harness.useTarget('test', { ...BASE_OPTIONS, include: ['src/app/repro/**/*.spec.ts'] });
19+
await harness.writeFiles({
20+
'src/app/repro/layout/layout.ts': `
21+
import { Component } from '@angular/core';
22+
@Component({ selector: 'app-layout', template: '<ng-content />' })
23+
export class Layout {}
24+
`,
25+
'src/app/repro/layout/index.ts': `
26+
export * from './layout';
27+
`,
28+
'src/app/repro/a/dialog.ts': `
29+
import { Component } from '@angular/core';
30+
import { Layout } from '../layout';
31+
@Component({
32+
selector: 'app-dialog',
33+
imports: [Layout],
34+
template: '<app-layout>dialog</app-layout>',
35+
})
36+
export class Dialog {}
37+
`,
38+
'src/app/repro/c/page.ts': `
39+
import { Component } from '@angular/core';
40+
import { Layout } from '../layout';
41+
@Component({
42+
selector: 'app-page',
43+
imports: [Layout],
44+
template: '<app-layout>page</app-layout>',
45+
})
46+
export class Page {}
47+
`,
48+
'src/app/repro/a/dialog.spec.ts': `
49+
import { TestBed } from '@angular/core/testing';
50+
import { Dialog } from './dialog';
51+
describe('a/dialog.spec.ts', () => {
52+
it('creates', () => {
53+
TestBed.configureTestingModule({ imports: [Dialog] });
54+
expect(TestBed.createComponent(Dialog).componentInstance).toBeTruthy();
55+
});
56+
});
57+
`,
58+
'src/app/repro/a/dialog-again.spec.ts': `
59+
import { TestBed } from '@angular/core/testing';
60+
import { Dialog } from './dialog';
61+
describe('a/dialog-again.spec.ts', () => {
62+
it('creates', () => {
63+
TestBed.configureTestingModule({ imports: [Dialog] });
64+
expect(TestBed.createComponent(Dialog).componentInstance).toBeTruthy();
65+
});
66+
});
67+
`,
68+
'src/app/repro/c/page.spec.ts': `
69+
import { TestBed } from '@angular/core/testing';
70+
import { Page } from './page';
71+
describe('c/page.spec.ts', () => {
72+
it('creates', () => {
73+
TestBed.configureTestingModule({ imports: [Page] });
74+
expect(TestBed.createComponent(Page).componentInstance).toBeTruthy();
75+
});
76+
});
77+
`,
78+
'src/app/repro/b/other.spec.ts': `
79+
import { TestBed } from '@angular/core/testing';
80+
import { Layout } from '../layout/layout';
81+
describe('async spec', () => {
82+
it('creates', async () => {
83+
TestBed.configureTestingModule({ imports: [Layout] });
84+
await Promise.resolve();
85+
expect(TestBed.createComponent(Layout).componentInstance).toBeTruthy();
86+
});
87+
});
88+
`,
89+
});
90+
const { result } = await harness.executeOnce();
91+
expect(result?.success).toBeTrue();
92+
});
93+
});
94+
});

0 commit comments

Comments
 (0)