Skip to content

Commit 1d296be

Browse files
committed
fix(@angular/build): ensure test hooks are registered in non-headless browser mode
This commit moves the `beforeEach` and `afterEach` hook registrations for TestBed cleanup to be outside the global setup guard. In non-headless browser environments, the setup file can be executed in different contexts where the global guard prevents the hooks from being registered, leading to inconsistent test behavior. This change ensures the cleanup hooks are always registered, improving reliability for headed browser test execution. Due to the nature of the issue, which only manifests in headed browser mode, automated testing in a CI environment is problematic.
1 parent 5e78117 commit 1d296be

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

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

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,13 @@ function createTestBedInitVirtualFile(
3636
import { afterEach, beforeEach } from 'vitest';
3737
${providersImport}
3838
39+
// The beforeEach and afterEach hooks are registered outside the globalThis guard.
40+
// This ensures that the hooks are always applied, even in non-isolated browser environments
41+
// where the setup file might be re-executed without re-initializing the global state.
42+
// Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29
43+
beforeEach(getCleanupHook(false));
44+
afterEach(getCleanupHook(true));
45+
3946
const ANGULAR_TESTBED_SETUP = Symbol.for('@angular/cli/testbed-setup');
4047
if (!globalThis[ANGULAR_TESTBED_SETUP]) {
4148
globalThis[ANGULAR_TESTBED_SETUP] = true;
@@ -44,10 +51,6 @@ function createTestBedInitVirtualFile(
4451
// In a non-isolated environment, this setup file can be executed multiple times.
4552
// The guard condition above ensures that the setup is only performed once.
4653
47-
// Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29
48-
beforeEach(getCleanupHook(false));
49-
afterEach(getCleanupHook(true));
50-
5154
@NgModule({
5255
providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}...providers],
5356
})

0 commit comments

Comments
 (0)