/
testability.ts
256 lines (222 loc) Β· 7.96 KB
/
testability.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/**
* @license
* Copyright Google Inc. 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 {Injectable} from '../di';
import {scheduleMicroTask} from '../util';
import {NgZone} from '../zone/ng_zone';
/**
* Testability API.
* `declare` keyword causes tsickle to generate externs, so these methods are
* not renamed by Closure Compiler.
* @experimental
*/
export declare interface PublicTestability {
isStable(): boolean;
whenStable(callback: Function): void;
findProviders(using: any, provider: string, exactMatch: boolean): any[];
}
export interface PendingMacrotask {
source: string;
isPeriodic: boolean;
delay?: number;
creationLocation: Error;
xhr?: XMLHttpRequest;
}
export type DoneCallback = (didWork: boolean, tasks?: PendingMacrotask[]) => void;
export type UpdateCallback = (tasks: PendingMacrotask[]) => boolean;
interface WaitCallback {
// Needs to be 'any' - setTimeout returns a number according to ES6, but
// on NodeJS it returns a Timer.
timeoutId: any;
doneCb: DoneCallback;
updateCb?: UpdateCallback;
}
/**
* The Testability service provides testing hooks that can be accessed from
* the browser and by services such as Protractor. Each bootstrapped Angular
* application on the page will have an instance of Testability.
* @experimental
*/
@Injectable()
export class Testability implements PublicTestability {
private _pendingCount: number = 0;
private _isZoneStable: boolean = true;
/**
* Whether any work was done since the last 'whenStable' callback. This is
* useful to detect if this could have potentially destabilized another
* component while it is stabilizing.
* @internal
*/
private _didWork: boolean = false;
private _callbacks: WaitCallback[] = [];
private taskTrackingZone: any;
constructor(private _ngZone: NgZone) {
this._watchAngularEvents();
_ngZone.run(() => { this.taskTrackingZone = Zone.current.get('TaskTrackingZone'); });
}
private _watchAngularEvents(): void {
this._ngZone.onUnstable.subscribe({
next: () => {
this._didWork = true;
this._isZoneStable = false;
}
});
this._ngZone.runOutsideAngular(() => {
this._ngZone.onStable.subscribe({
next: () => {
NgZone.assertNotInAngularZone();
scheduleMicroTask(() => {
this._isZoneStable = true;
this._runCallbacksIfReady();
});
}
});
});
}
/** @deprecated pending requests are now tracked with zones */
increasePendingRequestCount(): number {
this._pendingCount += 1;
this._didWork = true;
return this._pendingCount;
}
/** @deprecated pending requests are now tracked with zones */
decreasePendingRequestCount(): number {
this._pendingCount -= 1;
if (this._pendingCount < 0) {
throw new Error('pending async requests below zero');
}
this._runCallbacksIfReady();
return this._pendingCount;
}
isStable(): boolean {
return this._isZoneStable && this._pendingCount === 0 && !this._ngZone.hasPendingMacrotasks;
}
private _runCallbacksIfReady(): void {
if (this.isStable()) {
// Schedules the call backs in a new frame so that it is always async.
scheduleMicroTask(() => {
while (this._callbacks.length !== 0) {
let cb = (this._callbacks.pop() as WaitCallback);
clearTimeout(cb.timeoutId);
cb.doneCb(this._didWork);
}
this._didWork = false;
});
} else {
// Still not stable, send updates.
let pending = this.getPendingTasks();
this._callbacks = this._callbacks.filter((cb) => {
if (cb.updateCb && cb.updateCb(pending)) {
clearTimeout(cb.timeoutId);
return false;
}
return true;
});
this._didWork = true;
}
}
private getPendingTasks(): PendingMacrotask[] {
if (!this.taskTrackingZone) {
throw new Error('Task tracking zone required when using whenStable() with a timeout!');
}
return this.taskTrackingZone.macroTasks.map((t: Task) => {
return {
source: t.source,
isPeriodic: t.data.isPeriodic,
delay: t.data.delay,
// From TaskTrackingZone:
// https://github.com/angular/zone.js/blob/master/lib/zone-spec/task-tracking.ts#L40
creationLocation: (t as any).creationLocation as Error,
// Added by Zones for XHRs
// https://github.com/angular/zone.js/blob/master/lib/browser/browser.ts#L133
xhr: (t.data as any).target
};
});
}
private addCallback(cb: DoneCallback, timeout?: number, updateCb?: UpdateCallback) {
let timeoutId: any = -1;
if (timeout && timeout > 0) {
timeoutId = setTimeout(() => {
this._callbacks = this._callbacks.filter((cb) => cb.timeoutId !== timeoutId);
cb(this._didWork, this.getPendingTasks());
}, timeout);
}
this._callbacks.push(<WaitCallback>{doneCb: cb, timeoutId: timeoutId, updateCb: updateCb});
}
/**
* Wait for angular to be stable with a timeout. If the timeout is hit before Angular becomes
* stable, the callback receives a list of the macro tasks that were pending, otherwise null.
*
* @param doneCb The callback to invoke when Angular is stable or the timeout expires
* whichever comes first.
* @param timeout Optional. The maximum time to wait for Angular to become stable. If not
* specified, whenStable() will wait forever.
* @param updateCb Optional. If specified, this callback will be invoked whenever the set of
* pending macrotasks changes. If this callback returns true doneCb will not be invoked.
*
*/
whenStable(doneCb: DoneCallback, timeout?: number, updateCb?: UpdateCallback): void {
this.addCallback(doneCb, timeout, updateCb);
this._runCallbacksIfReady();
}
getPendingRequestCount(): number { return this._pendingCount; }
/** @deprecated use findProviders */
findBindings(using: any, provider: string, exactMatch: boolean): any[] {
// TODO(juliemr): implement.
return [];
}
findProviders(using: any, provider: string, exactMatch: boolean): any[] {
// TODO(juliemr): implement.
return [];
}
}
/**
* A global registry of {@link Testability} instances for specific elements.
* @experimental
*/
@Injectable()
export class TestabilityRegistry {
/** @internal */
_applications = new Map<any, Testability>();
constructor() { _testabilityGetter.addToWindow(this); }
registerApplication(token: any, testability: Testability) {
this._applications.set(token, testability);
}
getTestability(elem: any): Testability|null { return this._applications.get(elem) || null; }
getAllTestabilities(): Testability[] { return Array.from(this._applications.values()); }
getAllRootElements(): any[] { return Array.from(this._applications.keys()); }
findTestabilityInTree(elem: Node, findInAncestors: boolean = true): Testability|null {
return _testabilityGetter.findTestabilityInTree(this, elem, findInAncestors);
}
}
/**
* Adapter interface for retrieving the `Testability` service associated for a
* particular context.
*
* @experimental Testability apis are primarily intended to be used by e2e test tool vendors like
* the Protractor team.
*/
export interface GetTestability {
addToWindow(registry: TestabilityRegistry): void;
findTestabilityInTree(registry: TestabilityRegistry, elem: any, findInAncestors: boolean):
Testability|null;
}
class _NoopGetTestability implements GetTestability {
addToWindow(registry: TestabilityRegistry): void {}
findTestabilityInTree(registry: TestabilityRegistry, elem: any, findInAncestors: boolean):
Testability|null {
return null;
}
}
/**
* Set the {@link GetTestability} implementation used by the Angular testing framework.
* @experimental
*/
export function setTestabilityGetter(getter: GetTestability): void {
_testabilityGetter = getter;
}
let _testabilityGetter: GetTestability = new _NoopGetTestability();