From 1d296bea5b084e62f1192473197bcf9c12f7c1c6 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Thu, 13 Nov 2025 10:45:24 -0500 Subject: [PATCH] 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. --- .../unit-test/runners/vitest/build-options.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts index 408e1d6d4999..7736854b6ab8 100644 --- a/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts @@ -36,6 +36,13 @@ function createTestBedInitVirtualFile( import { afterEach, beforeEach } from 'vitest'; ${providersImport} + // The beforeEach and afterEach hooks are registered outside the globalThis guard. + // This ensures that the hooks are always applied, even in non-isolated browser environments + // where the setup file might be re-executed without re-initializing the global state. + // Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29 + beforeEach(getCleanupHook(false)); + afterEach(getCleanupHook(true)); + const ANGULAR_TESTBED_SETUP = Symbol.for('@angular/cli/testbed-setup'); if (!globalThis[ANGULAR_TESTBED_SETUP]) { globalThis[ANGULAR_TESTBED_SETUP] = true; @@ -44,10 +51,6 @@ function createTestBedInitVirtualFile( // In a non-isolated environment, this setup file can be executed multiple times. // The guard condition above ensures that the setup is only performed once. - // Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29 - beforeEach(getCleanupHook(false)); - afterEach(getCleanupHook(true)); - @NgModule({ providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}...providers], })