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], })