From d5592538e76c369070dccc05d4b75ffc8ff30385 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 TestBed cleanup hooks are always registered This commit moves the `beforeEach` and `afterEach` hook registrations for TestBed cleanup to be outside the global setup guard. In environments where test isolation is not strictly enforced (when `isolate: false`), the setup file can be executed multiple times in different contexts. The global guard would previously prevent the hooks from being re-registered, leading to inconsistent test behavior and potential state leakage between tests. This change ensures the cleanup hooks are always registered, improving the reliability and predictability of tests across all execution environments. --- .../builders/unit-test/runners/vitest/build-options.ts | 10 ++++++---- 1 file changed, 6 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..1c65d6fc4d50 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,12 @@ 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. + // 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 +50,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], })