Skip to content

Commit 0830f4f

Browse files
committed
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. (cherry picked from commit 79e52cc)
1 parent f7c4a4c commit 0830f4f

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ 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+
// Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29
42+
beforeEach(getCleanupHook(false));
43+
afterEach(getCleanupHook(true));
44+
3945
const ANGULAR_TESTBED_SETUP = Symbol.for('@angular/cli/testbed-setup');
4046
if (!globalThis[ANGULAR_TESTBED_SETUP]) {
4147
globalThis[ANGULAR_TESTBED_SETUP] = true;
@@ -44,10 +50,6 @@ function createTestBedInitVirtualFile(
4450
// In a non-isolated environment, this setup file can be executed multiple times.
4551
// The guard condition above ensures that the setup is only performed once.
4652
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-
5153
@NgModule({
5254
providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}...providers],
5355
})

0 commit comments

Comments
 (0)