From 6720fb68db2628f443875b42fee8c6d5cf7c3d00 Mon Sep 17 00:00:00 2001 From: Andrew Scott Date: Tue, 26 Aug 2025 11:32:07 -0700 Subject: [PATCH] fix(core): Explicit Zone CD in TestBed providers should not override TestBed error handler The internal error handler in TestBed rethrows errors to prevent them from being silently ignored in tests. Prior to this commit, tests which used `provideZoneChangeDetection` in the providers would override the internal error handler of TestBed and prevent these errors from being rethrown. BREAKING CHANGE: (test only) - Using `provideZoneChangeDetection` in the TestBed providers would previously prevent `TestBed` from rethrowing errors as it should. Errors in the test will now be rethrown, regardless of the usage of `provideZoneChangeDetection`. Tests should be adjusted to prevent or account for these errors. As in previous major versions, this behavior can be disabled with `rethrowApplicationErrors: false` in `configureTestingModule` as a last resort. --- .../test/pending_until_event_spec.ts | 2 +- .../core/src/application/application_ref.ts | 2 +- .../scheduling/ng_zone_scheduling.ts | 23 +---- .../scheduling/zoneless_scheduling_impl.ts | 2 +- packages/core/src/core_private_export.ts | 2 +- packages/core/src/defer/triggering.ts | 3 +- packages/core/src/error_handler.ts | 20 +++-- packages/core/src/event_emitter.ts | 2 +- packages/core/src/pending_tasks.ts | 78 +---------------- packages/core/src/pending_tasks_internal.ts | 87 +++++++++++++++++++ packages/core/src/platform/bootstrap.ts | 2 +- .../test/acceptance/pending_tasks_spec.ts | 2 +- packages/core/test/component_fixture_spec.ts | 2 + packages/core/test/defer_fixture_spec.ts | 2 +- .../core/testing/src/component_fixture.ts | 2 +- 15 files changed, 115 insertions(+), 116 deletions(-) create mode 100644 packages/core/src/pending_tasks_internal.ts diff --git a/packages/core/rxjs-interop/test/pending_until_event_spec.ts b/packages/core/rxjs-interop/test/pending_until_event_spec.ts index 2e82d3930df..be90b6a8aa7 100644 --- a/packages/core/rxjs-interop/test/pending_until_event_spec.ts +++ b/packages/core/rxjs-interop/test/pending_until_event_spec.ts @@ -7,7 +7,7 @@ */ import {EnvironmentInjector, ApplicationRef} from '../../src/core'; -import {PendingTasksInternal} from '../../src/pending_tasks'; +import {PendingTasksInternal} from '../../src/pending_tasks_internal'; import { BehaviorSubject, EMPTY, diff --git a/packages/core/src/application/application_ref.ts b/packages/core/src/application/application_ref.ts index fe03348efbf..0b731a31a16 100644 --- a/packages/core/src/application/application_ref.ts +++ b/packages/core/src/application/application_ref.ts @@ -32,7 +32,7 @@ import {ComponentFactory, ComponentRef} from '../linker/component_factory'; import {ComponentFactoryResolver} from '../linker/component_factory_resolver'; import {NgModuleRef} from '../linker/ng_module_factory'; import {ViewRef} from '../linker/view_ref'; -import {PendingTasksInternal} from '../pending_tasks'; +import {PendingTasksInternal} from '../pending_tasks_internal'; import {RendererFactory2} from '../render/api'; import {AfterRenderManager} from '../render3/after_render/manager'; import {ComponentFactory as R3ComponentFactory} from '../render3/component_ref'; diff --git a/packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts b/packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts index 00688946f62..e4ab35f5343 100644 --- a/packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts +++ b/packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts @@ -17,10 +17,11 @@ import { Injectable, InjectionToken, makeEnvironmentProviders, + provideEnvironmentInitializer, StaticProvider, } from '../../di'; import {RuntimeError, RuntimeErrorCode} from '../../errors'; -import {PendingTasksInternal} from '../../pending_tasks'; +import {PendingTasksInternal} from '../../pending_tasks_internal'; import {performanceMarkFeature} from '../../util/performance'; import {NgZone} from '../../zone'; import {InternalNgZoneOptions} from '../../zone/ng_zone'; @@ -132,26 +133,6 @@ export function internalProvideZoneChangeDetection({ provide: SCHEDULE_IN_ROOT_ZONE, useValue: scheduleInRootZone ?? SCHEDULE_IN_ROOT_ZONE_DEFAULT, }, - { - provide: INTERNAL_APPLICATION_ERROR_HANDLER, - useFactory: () => { - const zone = inject(NgZone); - const injector = inject(EnvironmentInjector); - let userErrorHandler: ErrorHandler; - return (e: unknown) => { - zone.runOutsideAngular(() => { - if (injector.destroyed && !userErrorHandler) { - setTimeout(() => { - throw e; - }); - } else { - userErrorHandler ??= injector.get(ErrorHandler); - userErrorHandler.handleError(e); - } - }); - }; - }, - }, ]; } diff --git a/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts b/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts index 278621ee9d6..fa82f244c2e 100644 --- a/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts +++ b/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts @@ -14,7 +14,7 @@ import {inject} from '../../di/injector_compatibility'; import {EnvironmentProviders} from '../../di/interface/provider'; import {makeEnvironmentProviders} from '../../di/provider_collection'; import {RuntimeError, RuntimeErrorCode, formatRuntimeError} from '../../errors'; -import {PendingTasksInternal} from '../../pending_tasks'; +import {PendingTasksInternal} from '../../pending_tasks_internal'; import { scheduleCallbackWithMicrotask, scheduleCallbackWithRafRace, diff --git a/packages/core/src/core_private_export.ts b/packages/core/src/core_private_export.ts index 3432dec5845..309cc005af0 100644 --- a/packages/core/src/core_private_export.ts +++ b/packages/core/src/core_private_export.ts @@ -121,7 +121,7 @@ export { resolveComponentResources as ɵresolveComponentResources, restoreComponentResolutionQueue as ɵrestoreComponentResolutionQueue, } from './metadata/resource_loading'; -export {PendingTasksInternal as ɵPendingTasksInternal} from './pending_tasks'; +export {PendingTasksInternal as ɵPendingTasksInternal} from './pending_tasks_internal'; export {ALLOW_MULTIPLE_PLATFORMS as ɵALLOW_MULTIPLE_PLATFORMS} from './platform/platform'; export {ENABLE_ROOT_COMPONENT_BOOTSTRAP as ɵENABLE_ROOT_COMPONENT_BOOTSTRAP} from './platform/bootstrap'; export {ReflectionCapabilities as ɵReflectionCapabilities} from './reflection/reflection_capabilities'; diff --git a/packages/core/src/defer/triggering.ts b/packages/core/src/defer/triggering.ts index bd8a0f86ee0..6095b73b5a0 100644 --- a/packages/core/src/defer/triggering.ts +++ b/packages/core/src/defer/triggering.ts @@ -21,7 +21,8 @@ import { getParentBlockHydrationQueue, isIncrementalHydrationEnabled, } from '../hydration/utils'; -import {PendingTasks, PendingTasksInternal} from '../pending_tasks'; +import {PendingTasks} from '../pending_tasks'; +import {PendingTasksInternal} from '../pending_tasks_internal'; import {assertLContainer} from '../render3/assert'; import {getComponentDef, getDirectiveDef, getPipeDef} from '../render3/def_getters'; import {getTemplateLocationDetails} from '../render3/instructions/element_validation'; diff --git a/packages/core/src/error_handler.ts b/packages/core/src/error_handler.ts index de60d74cf30..9157537d77a 100644 --- a/packages/core/src/error_handler.ts +++ b/packages/core/src/error_handler.ts @@ -14,6 +14,7 @@ import {makeEnvironmentProviders, provideEnvironmentInitializer} from './di/prov import {EnvironmentInjector} from './di/r3_injector'; import {DOCUMENT} from './document'; import {DestroyRef} from './linker/destroy_ref'; +import {NgZone} from './zone/ng_zone'; /** * Provides a hook for centralized exception handling. @@ -67,17 +68,20 @@ export const INTERNAL_APPLICATION_ERROR_HANDLER = new InjectionToken<(e: any) => factory: () => { // The user's error handler may depend on things that create a circular dependency // so we inject it lazily. + const zone = inject(NgZone); const injector = inject(EnvironmentInjector); let userErrorHandler: ErrorHandler; return (e: unknown) => { - if (injector.destroyed && !userErrorHandler) { - setTimeout(() => { - throw e; - }); - } else { - userErrorHandler ??= injector.get(ErrorHandler); - userErrorHandler.handleError(e); - } + zone.runOutsideAngular(() => { + if (injector.destroyed && !userErrorHandler) { + setTimeout(() => { + throw e; + }); + } else { + userErrorHandler ??= injector.get(ErrorHandler); + userErrorHandler.handleError(e); + } + }); }; }, }, diff --git a/packages/core/src/event_emitter.ts b/packages/core/src/event_emitter.ts index 7ac64d981de..7f4c55cd909 100644 --- a/packages/core/src/event_emitter.ts +++ b/packages/core/src/event_emitter.ts @@ -13,7 +13,7 @@ import {OutputRef} from './authoring/output/output_ref'; import {isInInjectionContext} from './di/contextual'; import {inject} from './di/injector_compatibility'; import {DestroyRef} from './linker/destroy_ref'; -import {PendingTasksInternal} from './pending_tasks'; +import {PendingTasksInternal} from './pending_tasks_internal'; /** * Use in components with the `@Output` directive to emit custom events diff --git a/packages/core/src/pending_tasks.ts b/packages/core/src/pending_tasks.ts index e9809c9cbd5..0f1708903ef 100644 --- a/packages/core/src/pending_tasks.ts +++ b/packages/core/src/pending_tasks.ts @@ -6,90 +6,14 @@ * found in the LICENSE file at https://angular.dev/license */ -import {BehaviorSubject, Observable} from 'rxjs'; - import {inject} from './di/injector_compatibility'; import {ɵɵdefineInjectable} from './di/interface/defs'; -import {OnDestroy} from './interface/lifecycle_hooks'; import { ChangeDetectionScheduler, NotificationSource, } from './change_detection/scheduling/zoneless_scheduling'; import {INTERNAL_APPLICATION_ERROR_HANDLER} from './error_handler'; - -/** - * Internal implementation of the pending tasks service. - */ -export class PendingTasksInternal implements OnDestroy { - private taskId = 0; - private pendingTasks = new Set(); - private destroyed = false; - - private pendingTask = new BehaviorSubject(false); - - get hasPendingTasks(): boolean { - // Accessing the value of a closed `BehaviorSubject` throws an error. - return this.destroyed ? false : this.pendingTask.value; - } - - /** - * In case the service is about to be destroyed, return a self-completing observable. - * Otherwise, return the observable that emits the current state of pending tasks. - */ - get hasPendingTasksObservable(): Observable { - if (this.destroyed) { - // Manually creating the observable pulls less symbols from RxJS than `of(false)`. - return new Observable((subscriber) => { - subscriber.next(false); - subscriber.complete(); - }); - } - - return this.pendingTask; - } - - add(): number { - // Emitting a value to a closed subject throws an error. - if (!this.hasPendingTasks && !this.destroyed) { - this.pendingTask.next(true); - } - const taskId = this.taskId++; - this.pendingTasks.add(taskId); - return taskId; - } - - has(taskId: number): boolean { - return this.pendingTasks.has(taskId); - } - - remove(taskId: number): void { - this.pendingTasks.delete(taskId); - if (this.pendingTasks.size === 0 && this.hasPendingTasks) { - this.pendingTask.next(false); - } - } - - ngOnDestroy(): void { - this.pendingTasks.clear(); - if (this.hasPendingTasks) { - this.pendingTask.next(false); - } - // We call `unsubscribe()` to release observers, as users may forget to - // unsubscribe manually when subscribing to `isStable`. We do not call - // `complete()` because it is unsafe; if someone subscribes using the `first` - // operator and the observable completes before emitting a value, - // RxJS will throw an error. - this.destroyed = true; - this.pendingTask.unsubscribe(); - } - - /** @nocollapse */ - static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ - token: PendingTasksInternal, - providedIn: 'root', - factory: () => new PendingTasksInternal(), - }); -} +import {PendingTasksInternal} from './pending_tasks_internal'; /** * Service that keeps track of pending tasks contributing to the stableness of Angular diff --git a/packages/core/src/pending_tasks_internal.ts b/packages/core/src/pending_tasks_internal.ts new file mode 100644 index 00000000000..91d081db45f --- /dev/null +++ b/packages/core/src/pending_tasks_internal.ts @@ -0,0 +1,87 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import {BehaviorSubject, Observable} from 'rxjs'; + +import {ɵɵdefineInjectable} from './di/interface/defs'; +import {OnDestroy} from './interface/lifecycle_hooks'; + +/** + * Internal implementation of the pending tasks service. + */ + +export class PendingTasksInternal implements OnDestroy { + private taskId = 0; + private pendingTasks = new Set(); + private destroyed = false; + + private pendingTask = new BehaviorSubject(false); + + get hasPendingTasks(): boolean { + // Accessing the value of a closed `BehaviorSubject` throws an error. + return this.destroyed ? false : this.pendingTask.value; + } + + /** + * In case the service is about to be destroyed, return a self-completing observable. + * Otherwise, return the observable that emits the current state of pending tasks. + */ + get hasPendingTasksObservable(): Observable { + if (this.destroyed) { + // Manually creating the observable pulls less symbols from RxJS than `of(false)`. + return new Observable((subscriber) => { + subscriber.next(false); + subscriber.complete(); + }); + } + + return this.pendingTask; + } + + add(): number { + // Emitting a value to a closed subject throws an error. + if (!this.hasPendingTasks && !this.destroyed) { + this.pendingTask.next(true); + } + const taskId = this.taskId++; + this.pendingTasks.add(taskId); + return taskId; + } + + has(taskId: number): boolean { + return this.pendingTasks.has(taskId); + } + + remove(taskId: number): void { + this.pendingTasks.delete(taskId); + if (this.pendingTasks.size === 0 && this.hasPendingTasks) { + this.pendingTask.next(false); + } + } + + ngOnDestroy(): void { + this.pendingTasks.clear(); + if (this.hasPendingTasks) { + this.pendingTask.next(false); + } + // We call `unsubscribe()` to release observers, as users may forget to + // unsubscribe manually when subscribing to `isStable`. We do not call + // `complete()` because it is unsafe; if someone subscribes using the `first` + // operator and the observable completes before emitting a value, + // RxJS will throw an error. + this.destroyed = true; + this.pendingTask.unsubscribe(); + } + + /** @nocollapse */ + static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ + token: PendingTasksInternal, + providedIn: 'root', + factory: () => new PendingTasksInternal(), + }); +} diff --git a/packages/core/src/platform/bootstrap.ts b/packages/core/src/platform/bootstrap.ts index bd38d62da3e..f7947abc771 100644 --- a/packages/core/src/platform/bootstrap.ts +++ b/packages/core/src/platform/bootstrap.ts @@ -26,7 +26,7 @@ import {InjectionToken, Injector} from '../di'; import {InternalNgModuleRef, NgModuleRef} from '../linker/ng_module_factory'; import {stringify} from '../util/stringify'; import {isPromise} from '../util/lang'; -import {PendingTasksInternal} from '../pending_tasks'; +import {PendingTasksInternal} from '../pending_tasks_internal'; /** * InjectionToken to control root component bootstrap behavior. diff --git a/packages/core/test/acceptance/pending_tasks_spec.ts b/packages/core/test/acceptance/pending_tasks_spec.ts index ef207cf2423..f706645cc44 100644 --- a/packages/core/test/acceptance/pending_tasks_spec.ts +++ b/packages/core/test/acceptance/pending_tasks_spec.ts @@ -11,7 +11,7 @@ import {TestBed} from '../../testing'; import {EMPTY, firstValueFrom, of} from 'rxjs'; import {map, withLatestFrom} from 'rxjs/operators'; -import {PendingTasksInternal} from '../../src/pending_tasks'; +import {PendingTasksInternal} from '../../src/pending_tasks_internal'; describe('PendingTasks', () => { it('should wait until all tasks are completed', async () => { diff --git a/packages/core/test/component_fixture_spec.ts b/packages/core/test/component_fixture_spec.ts index 590729d4d07..daed9f99274 100644 --- a/packages/core/test/component_fixture_spec.ts +++ b/packages/core/test/component_fixture_spec.ts @@ -16,6 +16,7 @@ import { NgZone, createComponent, provideZonelessChangeDetection, + provideZoneChangeDetection, signal, } from '../src/core'; import { @@ -428,6 +429,7 @@ describe('ComponentFixture', () => { class Blank {} it('rejects whenStable promise when errors happen during appRef.tick', async () => { + TestBed.configureTestingModule({providers: [provideZoneChangeDetection()]}); const fixture = TestBed.createComponent(Blank); const throwingThing = createComponent(ThrowingThing, { environmentInjector: TestBed.inject(EnvironmentInjector), diff --git a/packages/core/test/defer_fixture_spec.ts b/packages/core/test/defer_fixture_spec.ts index b1a00a2e6c4..835e9a6d3e5 100644 --- a/packages/core/test/defer_fixture_spec.ts +++ b/packages/core/test/defer_fixture_spec.ts @@ -8,7 +8,7 @@ import {ɵPLATFORM_BROWSER_ID as PLATFORM_BROWSER_ID} from '@angular/common'; import {Component, inject, PLATFORM_ID, ViewContainerRef} from '../src/core'; -import {PendingTasksInternal} from '../src/pending_tasks'; +import {PendingTasksInternal} from '../src/pending_tasks_internal'; import {DeferBlockBehavior, DeferBlockState, TestBed} from '../testing'; import {expect} from '@angular/private/testing/matchers'; diff --git a/packages/core/testing/src/component_fixture.ts b/packages/core/testing/src/component_fixture.ts index 190d6194dc5..f2fc416f04c 100644 --- a/packages/core/testing/src/component_fixture.ts +++ b/packages/core/testing/src/component_fixture.ts @@ -26,7 +26,7 @@ import { ɵChangeDetectionScheduler, ɵNotificationSource, } from '../../src/core'; -import {PendingTasksInternal} from '../../src/pending_tasks'; +import {PendingTasksInternal} from '../../src/pending_tasks_internal'; import {TestBedApplicationErrorHandler} from './application_error_handler'; import {DeferBlockFixture} from './defer';