Skip to content

Commit c272b38

Browse files
JeanMechealan-agius4
authored andcommitted
fix(@angular/build): flush pending JIT NgModule scopes in Vitest beforeAll
In JIT mode (`aot: false`), `@NgModule` enqueues its module onto Angular's delayed scoping queue once when the class is evaluated. `TestBed` only flushes that queue once per realm (`checkGlobalCompilationFinished`), assuming all spec files were evaluated before the first test. With `@angular/build:unit-test` running Vitest in non-isolated mode (`isolate: false` by default), spec files are imported sequentially into the same worker. If a later spec file imports an `@NgModule` without compiling any component, `TestBed.resetTestingModule()` clears the pending scoping queue via `resetCompiledComponents()`, permanently losing the module's scope for subsequent specs (`NG0303` / `NG0302`). Registering `beforeAll(() => ɵflushModuleScopingQueueAsMuchAsPossible())` in the Vitest TestBed setup file flushes file-scope `@NgModule`s right after each spec file's imports are evaluated and before any `beforeEach` or `it` runs, without affecting test-local `@NgModule`s or incurring work in AOT mode. Fixes angular/angular#72266 (cherry picked from commit 3f2f357)
1 parent 78afeda commit c272b38

2 files changed

Lines changed: 138 additions & 3 deletions

File tree

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,22 @@ function createTestBedInitVirtualFile(
4949
return `
5050
${hasLocalize ? "import '@angular/localize/init';" : ''}
5151
// Initialize the Angular testing environment
52-
import { NgModule, provideZoneChangeDetection } from '@angular/core';
52+
import {
53+
NgModule,
54+
provideZoneChangeDetection,
55+
ɵflushModuleScopingQueueAsMuchAsPossible as flushModuleScopingQueue,
56+
} from '@angular/core';
5357
import { getTestBed, ɵgetCleanupHook as getCleanupHook, TestComponentRenderer } from '@angular/core/testing';
5458
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
5559
import { ɵgetDOM } from '@angular/common';
56-
import { afterEach, beforeEach } from 'vitest';
60+
import { afterEach, beforeAll, beforeEach } from 'vitest';
5761
${providersImport}
5862
59-
// The beforeEach and afterEach hooks are registered outside the globalThis guard.
63+
// The beforeAll, beforeEach, and afterEach hooks are registered outside the globalThis guard.
6064
// This ensures that the hooks are always applied, even in non-isolated browser environments.
6165
// Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29
66+
// Flush pending JIT NgModule scopes evaluated when each spec file is imported in a shared worker.
67+
beforeAll(() => flushModuleScopingQueue());
6268
beforeEach(getCleanupHook(false));
6369
afterEach(getCleanupHook(true));
6470

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

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,5 +108,134 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => {
108108
const { result } = await harness.executeOnce();
109109
expect(result?.success).toBeTrue();
110110
});
111+
112+
it('should preserve JIT NgModule scopes across spec files when isolate is false', async () => {
113+
setupApplicationTarget(harness, { aot: false });
114+
115+
harness.writeFile(
116+
'vitest-base.config.mts',
117+
`
118+
import { defineConfig } from 'vitest/config';
119+
import { BaseSequencer, type TestSpecification } from 'vitest/node';
120+
121+
class FileNameSequencer extends BaseSequencer {
122+
override async sort(files: TestSpecification[]) {
123+
return [...files].sort((a, b) => a.moduleId.localeCompare(b.moduleId));
124+
}
125+
}
126+
127+
export default defineConfig({
128+
test: {
129+
fileParallelism: false,
130+
sequence: { sequencer: FileNameSequencer },
131+
},
132+
});
133+
`,
134+
);
135+
136+
harness.writeFile(
137+
'src/app/legacy.ts',
138+
`
139+
import { CommonModule } from '@angular/common';
140+
import { Component, Injectable, NgModule, input } from '@angular/core';
141+
142+
@Component({
143+
selector: 'app-legacy-list',
144+
standalone: false,
145+
template: '<ul><li *ngFor="let item of items" class="item">{{ item }}</li></ul>',
146+
})
147+
export class LegacyListComponent {
148+
items = ['a', 'b'];
149+
}
150+
151+
@NgModule({
152+
imports: [CommonModule],
153+
declarations: [LegacyListComponent],
154+
exports: [LegacyListComponent],
155+
})
156+
export class LegacyModule {}
157+
158+
@Component({
159+
selector: 'app-panel',
160+
imports: [LegacyModule],
161+
template: '<app-legacy-list />',
162+
})
163+
export class PanelComponent {
164+
label = input('');
165+
}
166+
167+
@Injectable({ providedIn: 'root' })
168+
export class PanelRegistryService {
169+
isPanel(instance: unknown) {
170+
return instance instanceof PanelComponent;
171+
}
172+
}
173+
`,
174+
);
175+
176+
harness.writeFile(
177+
'src/app/1-unrelated.spec.ts',
178+
`
179+
import { Injectable } from '@angular/core';
180+
import { TestBed } from '@angular/core/testing';
181+
182+
@Injectable({ providedIn: 'root' })
183+
class UnrelatedService {
184+
value = 42;
185+
}
186+
187+
describe('UnrelatedService', () => {
188+
it('is injectable', () => {
189+
expect(TestBed.inject(UnrelatedService).value).toBe(42);
190+
});
191+
});
192+
`,
193+
);
194+
195+
harness.writeFile(
196+
'src/app/2-registry.spec.ts',
197+
`
198+
import { TestBed } from '@angular/core/testing';
199+
import { PanelRegistryService } from './legacy';
200+
201+
describe('PanelRegistryService', () => {
202+
it('recognises non-panels', () => {
203+
expect(TestBed.inject(PanelRegistryService).isPanel({})).toBe(false);
204+
});
205+
});
206+
`,
207+
);
208+
209+
harness.writeFile(
210+
'src/app/3-panel.spec.ts',
211+
`
212+
import { TestBed } from '@angular/core/testing';
213+
import { PanelComponent } from './legacy';
214+
215+
describe('PanelComponent', () => {
216+
it('renders items using NgModule scope', () => {
217+
const fixture = TestBed.createComponent(PanelComponent);
218+
fixture.detectChanges();
219+
expect(fixture.nativeElement.querySelectorAll('.item').length).toBe(2);
220+
});
221+
});
222+
`,
223+
);
224+
225+
harness.useTarget('test', {
226+
...BASE_OPTIONS,
227+
runner: 'vitest' as any,
228+
runnerConfig: true,
229+
isolate: false,
230+
include: [
231+
'src/app/1-unrelated.spec.ts',
232+
'src/app/2-registry.spec.ts',
233+
'src/app/3-panel.spec.ts',
234+
],
235+
});
236+
237+
const { result } = await harness.executeOnce();
238+
expect(result?.success).toBeTrue();
239+
});
111240
});
112241
});

0 commit comments

Comments
 (0)