-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
component_fixture.ts
242 lines (216 loc) Β· 7.6 KB
/
component_fixture.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/**
* @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.io/license
*/
import {ApplicationRef, ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, getDebugNode, inject, NgZone, RendererFactory2, Ι΅DeferBlockDetails as DeferBlockDetails, Ι΅EffectScheduler as EffectScheduler, Ι΅getDeferBlocks as getDeferBlocks, Ι΅NoopNgZone as NoopNgZone} from '@angular/core';
import {Subscription} from 'rxjs';
import {DeferBlockFixture} from './defer';
import {ComponentFixtureAutoDetect, ComponentFixtureNoNgZone} from './test_bed_common';
/**
* Fixture for debugging and testing a component.
*
* @publicApi
*/
export class ComponentFixture<T> {
/**
* The DebugElement associated with the root element of this component.
*/
debugElement: DebugElement;
/**
* The instance of the root component class.
*/
componentInstance: T;
/**
* The native element at the root of the component.
*/
nativeElement: any;
/**
* The ElementRef for the element at the root of the component.
*/
elementRef: ElementRef;
/**
* The ChangeDetectorRef for the component
*/
changeDetectorRef: ChangeDetectorRef;
private _renderer: RendererFactory2|null|undefined;
private _isStable: boolean = true;
private _isDestroyed: boolean = false;
private _resolve: ((result: boolean) => void)|null = null;
private _promise: Promise<boolean>|null = null;
private readonly noZoneOptionIsSet = inject(ComponentFixtureNoNgZone, {optional: true});
private _ngZone: NgZone = this.noZoneOptionIsSet ? new NoopNgZone() : inject(NgZone);
private _autoDetect = inject(ComponentFixtureAutoDetect, {optional: true}) ?? false;
private effectRunner = inject(EffectScheduler);
private _subscriptions = new Subscription();
// Inject ApplicationRef to ensure NgZone stableness causes after render hooks to run
// This will likely happen as a result of fixture.detectChanges because it calls ngZone.run
// This is a crazy way of doing things but hey, it's the world we live in.
// The zoneless scheduler should instead do this more imperatively by attaching
// the `ComponentRef` to `ApplicationRef` and calling `appRef.tick` as the `detectChanges`
// behavior.
private appRef = inject(ApplicationRef);
// TODO(atscott): Remove this from public API
public ngZone = this.noZoneOptionIsSet ? null : this._ngZone;
/** @nodoc */
constructor(public componentRef: ComponentRef<T>) {
this.changeDetectorRef = componentRef.changeDetectorRef;
this.elementRef = componentRef.location;
this.debugElement = <DebugElement>getDebugNode(this.elementRef.nativeElement);
this.componentInstance = componentRef.instance;
this.nativeElement = this.elementRef.nativeElement;
this.componentRef = componentRef;
this.setupNgZone();
}
private setupNgZone() {
// Create subscriptions outside the NgZone so that the callbacks run outside
// of NgZone.
this._ngZone.runOutsideAngular(() => {
this._subscriptions.add(this._ngZone.onUnstable.subscribe({
next: () => {
this._isStable = false;
}
}));
this._subscriptions.add(this._ngZone.onMicrotaskEmpty.subscribe({
next: () => {
if (this._autoDetect) {
// Do a change detection run with checkNoChanges set to true to check
// there are no changes on the second run.
this.detectChanges(true);
}
}
}));
this._subscriptions.add(this._ngZone.onStable.subscribe({
next: () => {
this._isStable = true;
// Check whether there is a pending whenStable() completer to resolve.
if (this._promise !== null) {
// If so check whether there are no pending macrotasks before resolving.
// Do this check in the next tick so that ngZone gets a chance to update the state of
// pending macrotasks.
queueMicrotask(() => {
if (!this._ngZone.hasPendingMacrotasks) {
if (this._promise !== null) {
this._resolve!(true);
this._resolve = null;
this._promise = null;
}
}
});
}
}
}));
this._subscriptions.add(this._ngZone.onError.subscribe({
next: (error: any) => {
throw error;
}
}));
});
}
private _tick(checkNoChanges: boolean) {
this.changeDetectorRef.detectChanges();
if (checkNoChanges) {
this.checkNoChanges();
}
}
/**
* Trigger a change detection cycle for the component.
*/
detectChanges(checkNoChanges: boolean = true): void {
this.effectRunner.flush();
// Run the change detection inside the NgZone so that any async tasks as part of the change
// detection are captured by the zone and can be waited for in isStable.
this._ngZone.run(() => {
this._tick(checkNoChanges);
});
// Run any effects that were created/dirtied during change detection. Such effects might become
// dirty in response to input signals changing.
this.effectRunner.flush();
}
/**
* Do a change detection run to make sure there were no changes.
*/
checkNoChanges(): void {
this.changeDetectorRef.checkNoChanges();
}
/**
* Set whether the fixture should autodetect changes.
*
* Also runs detectChanges once so that any existing change is detected.
*/
autoDetectChanges(autoDetect: boolean = true) {
if (this.noZoneOptionIsSet) {
throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set');
}
this._autoDetect = autoDetect;
this.detectChanges();
}
/**
* Return whether the fixture is currently stable or has async tasks that have not been completed
* yet.
*/
isStable(): boolean {
return this._isStable && !this._ngZone.hasPendingMacrotasks;
}
/**
* Get a promise that resolves when the fixture is stable.
*
* This can be used to resume testing after events have triggered asynchronous activity or
* asynchronous change detection.
*/
whenStable(): Promise<any> {
if (this.isStable()) {
return Promise.resolve(false);
} else if (this._promise !== null) {
return this._promise;
} else {
this._promise = new Promise(res => {
this._resolve = res;
});
return this._promise;
}
}
/**
* Retrieves all defer block fixtures in the component fixture.
*
* @developerPreview
*/
getDeferBlocks(): Promise<DeferBlockFixture[]> {
const deferBlocks: DeferBlockDetails[] = [];
const lView = (this.componentRef.hostView as any)['_lView'];
getDeferBlocks(lView, deferBlocks);
const deferBlockFixtures = [];
for (const block of deferBlocks) {
deferBlockFixtures.push(new DeferBlockFixture(block, this));
}
return Promise.resolve(deferBlockFixtures);
}
private _getRenderer() {
if (this._renderer === undefined) {
this._renderer = this.componentRef.injector.get(RendererFactory2, null);
}
return this._renderer as RendererFactory2 | null;
}
/**
* Get a promise that resolves when the ui state is stable following animations.
*/
whenRenderingDone(): Promise<any> {
const renderer = this._getRenderer();
if (renderer && renderer.whenRenderingDone) {
return renderer.whenRenderingDone();
}
return this.whenStable();
}
/**
* Trigger component destruction.
*/
destroy(): void {
if (!this._isDestroyed) {
this.componentRef.destroy();
this._subscriptions.unsubscribe();
this._isDestroyed = true;
}
}
}