| 94 | */ |
| 95 | @Injectable() |
| 96 | export class Testability implements PublicTestability { |
| 97 | private _isZoneStable: boolean = true; |
| 98 | private _callbacks: WaitCallback[] = []; |
| 99 | |
| 100 | private _taskTrackingZone: {macroTasks: Task[]} | null = null; |
| 101 | |
| 102 | private _destroyRef?: DestroyRef; |
| 103 | |
| 104 | private readonly pendingTasksInternal = inject(PendingTasksInternal); |
| 105 | private readonly _usePendingTasks = inject(USE_PENDING_TASKS); |
| 106 | constructor( |
| 107 | private _ngZone: NgZone, |
| 108 | private registry: TestabilityRegistry, |
| 109 | @Inject(TESTABILITY_GETTER) testabilityGetter: GetTestability, |
| 110 | ) { |
| 111 | // Attempt to retrieve a `DestroyRef` optionally. |
| 112 | // For backwards compatibility reasons, this cannot be required. |
| 113 | if (isInInjectionContext()) { |
| 114 | this._destroyRef = inject(DestroyRef, {optional: true}) ?? undefined; |
| 115 | } |
| 116 | |
| 117 | // If there was no Testability logic registered in the global scope |
| 118 | // before, register the current testability getter as a global one. |
| 119 | if (!_testabilityGetter) { |
| 120 | setTestabilityGetter(testabilityGetter); |
| 121 | testabilityGetter.addToWindow(registry); |
| 122 | } |
| 123 | this._watchAngularEvents(); |
| 124 | _ngZone.run(() => { |
| 125 | this._taskTrackingZone = |
| 126 | typeof Zone == 'undefined' ? null : Zone.current.get('TaskTrackingZone'); |
| 127 | }); |
| 128 | } |
| 129 | |
| 130 | private _watchAngularEvents(): void { |
| 131 | const onUnstableSubscription = this._ngZone.onUnstable.subscribe({ |
| 132 | next: () => { |
| 133 | this._isZoneStable = false; |
| 134 | }, |
| 135 | }); |
| 136 | |
| 137 | let pendingTasksSubscription: Subscription | undefined; |
| 138 | let onStableSubscription: Subscription; |
| 139 | |
| 140 | this._ngZone.runOutsideAngular(() => { |
| 141 | if (this._usePendingTasks) { |
| 142 | pendingTasksSubscription = this.pendingTasksInternal.hasPendingTasksObservable.subscribe( |
| 143 | () => { |
| 144 | if (this.isStable()) { |
| 145 | this._ngZone.runOutsideAngular(() => { |
| 146 | this._runCallbacksIfReady(); |
| 147 | }); |
| 148 | } |
| 149 | }, |
| 150 | ); |
| 151 | } |
| 152 | |
| 153 | onStableSubscription = this._ngZone.onStable.subscribe({ |