source: trip-planner-front/node_modules/zone.js/bundles/zone-testing.umd.js@ b738035

Last change on this file since b738035 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 103.7 KB
Line 
1'use strict';
2var __spreadArrays = (this && this.__spreadArrays) || function () {
3 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
4 for (var r = Array(s), k = 0, i = 0; i < il; i++)
5 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
6 r[k] = a[j];
7 return r;
8};
9/**
10 * @license Angular v12.0.0-next.0
11 * (c) 2010-2020 Google LLC. https://angular.io/
12 * License: MIT
13 */
14(function (factory) {
15 typeof define === 'function' && define.amd ? define(factory) :
16 factory();
17}((function () {
18 'use strict';
19 /**
20 * @license
21 * Copyright Google LLC All Rights Reserved.
22 *
23 * Use of this source code is governed by an MIT-style license that can be
24 * found in the LICENSE file at https://angular.io/license
25 */
26 /**
27 * @fileoverview
28 * @suppress {globalThis}
29 */
30 var NEWLINE = '\n';
31 var IGNORE_FRAMES = {};
32 var creationTrace = '__creationTrace__';
33 var ERROR_TAG = 'STACKTRACE TRACKING';
34 var SEP_TAG = '__SEP_TAG__';
35 var sepTemplate = SEP_TAG + '@[native]';
36 var LongStackTrace = /** @class */ (function () {
37 function LongStackTrace() {
38 this.error = getStacktrace();
39 this.timestamp = new Date();
40 }
41 return LongStackTrace;
42 }());
43 function getStacktraceWithUncaughtError() {
44 return new Error(ERROR_TAG);
45 }
46 function getStacktraceWithCaughtError() {
47 try {
48 throw getStacktraceWithUncaughtError();
49 }
50 catch (err) {
51 return err;
52 }
53 }
54 // Some implementations of exception handling don't create a stack trace if the exception
55 // isn't thrown, however it's faster not to actually throw the exception.
56 var error = getStacktraceWithUncaughtError();
57 var caughtError = getStacktraceWithCaughtError();
58 var getStacktrace = error.stack ?
59 getStacktraceWithUncaughtError :
60 (caughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
61 function getFrames(error) {
62 return error.stack ? error.stack.split(NEWLINE) : [];
63 }
64 function addErrorStack(lines, error) {
65 var trace = getFrames(error);
66 for (var i = 0; i < trace.length; i++) {
67 var frame = trace[i];
68 // Filter out the Frames which are part of stack capturing.
69 if (!IGNORE_FRAMES.hasOwnProperty(frame)) {
70 lines.push(trace[i]);
71 }
72 }
73 }
74 function renderLongStackTrace(frames, stack) {
75 var longTrace = [stack ? stack.trim() : ''];
76 if (frames) {
77 var timestamp = new Date().getTime();
78 for (var i = 0; i < frames.length; i++) {
79 var traceFrames = frames[i];
80 var lastTime = traceFrames.timestamp;
81 var separator = "____________________Elapsed " + (timestamp - lastTime.getTime()) + " ms; At: " + lastTime;
82 separator = separator.replace(/[^\w\d]/g, '_');
83 longTrace.push(sepTemplate.replace(SEP_TAG, separator));
84 addErrorStack(longTrace, traceFrames.error);
85 timestamp = lastTime.getTime();
86 }
87 }
88 return longTrace.join(NEWLINE);
89 }
90 // if Error.stackTraceLimit is 0, means stack trace
91 // is disabled, so we don't need to generate long stack trace
92 // this will improve performance in some test(some test will
93 // set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
94 function stackTracesEnabled() {
95 // Cast through any since this property only exists on Error in the nodejs
96 // typings.
97 return Error.stackTraceLimit > 0;
98 }
99 Zone['longStackTraceZoneSpec'] = {
100 name: 'long-stack-trace',
101 longStackTraceLimit: 10,
102 // add a getLongStackTrace method in spec to
103 // handle handled reject promise error.
104 getLongStackTrace: function (error) {
105 if (!error) {
106 return undefined;
107 }
108 var trace = error[Zone.__symbol__('currentTaskTrace')];
109 if (!trace) {
110 return error.stack;
111 }
112 return renderLongStackTrace(trace, error.stack);
113 },
114 onScheduleTask: function (parentZoneDelegate, currentZone, targetZone, task) {
115 if (stackTracesEnabled()) {
116 var currentTask = Zone.currentTask;
117 var trace = currentTask && currentTask.data && currentTask.data[creationTrace] || [];
118 trace = [new LongStackTrace()].concat(trace);
119 if (trace.length > this.longStackTraceLimit) {
120 trace.length = this.longStackTraceLimit;
121 }
122 if (!task.data)
123 task.data = {};
124 if (task.type === 'eventTask') {
125 // Fix issue https://github.com/angular/zone.js/issues/1195,
126 // For event task of browser, by default, all task will share a
127 // singleton instance of data object, we should create a new one here
128 // The cast to `any` is required to workaround a closure bug which wrongly applies
129 // URL sanitization rules to .data access.
130 task.data = Object.assign({}, task.data);
131 }
132 task.data[creationTrace] = trace;
133 }
134 return parentZoneDelegate.scheduleTask(targetZone, task);
135 },
136 onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
137 if (stackTracesEnabled()) {
138 var parentTask = Zone.currentTask || error.task;
139 if (error instanceof Error && parentTask) {
140 var longStack = renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
141 try {
142 error.stack = error.longStack = longStack;
143 }
144 catch (err) {
145 }
146 }
147 }
148 return parentZoneDelegate.handleError(targetZone, error);
149 }
150 };
151 function captureStackTraces(stackTraces, count) {
152 if (count > 0) {
153 stackTraces.push(getFrames((new LongStackTrace()).error));
154 captureStackTraces(stackTraces, count - 1);
155 }
156 }
157 function computeIgnoreFrames() {
158 if (!stackTracesEnabled()) {
159 return;
160 }
161 var frames = [];
162 captureStackTraces(frames, 2);
163 var frames1 = frames[0];
164 var frames2 = frames[1];
165 for (var i = 0; i < frames1.length; i++) {
166 var frame1 = frames1[i];
167 if (frame1.indexOf(ERROR_TAG) == -1) {
168 var match = frame1.match(/^\s*at\s+/);
169 if (match) {
170 sepTemplate = match[0] + SEP_TAG + ' (http://localhost)';
171 break;
172 }
173 }
174 }
175 for (var i = 0; i < frames1.length; i++) {
176 var frame1 = frames1[i];
177 var frame2 = frames2[i];
178 if (frame1 === frame2) {
179 IGNORE_FRAMES[frame1] = true;
180 }
181 else {
182 break;
183 }
184 }
185 }
186 computeIgnoreFrames();
187 /**
188 * @license
189 * Copyright Google LLC All Rights Reserved.
190 *
191 * Use of this source code is governed by an MIT-style license that can be
192 * found in the LICENSE file at https://angular.io/license
193 */
194 var ProxyZoneSpec = /** @class */ (function () {
195 function ProxyZoneSpec(defaultSpecDelegate) {
196 if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
197 this.defaultSpecDelegate = defaultSpecDelegate;
198 this.name = 'ProxyZone';
199 this._delegateSpec = null;
200 this.properties = { 'ProxyZoneSpec': this };
201 this.propertyKeys = null;
202 this.lastTaskState = null;
203 this.isNeedToTriggerHasTask = false;
204 this.tasks = [];
205 this.setDelegate(defaultSpecDelegate);
206 }
207 ProxyZoneSpec.get = function () {
208 return Zone.current.get('ProxyZoneSpec');
209 };
210 ProxyZoneSpec.isLoaded = function () {
211 return ProxyZoneSpec.get() instanceof ProxyZoneSpec;
212 };
213 ProxyZoneSpec.assertPresent = function () {
214 if (!ProxyZoneSpec.isLoaded()) {
215 throw new Error("Expected to be running in 'ProxyZone', but it was not found.");
216 }
217 return ProxyZoneSpec.get();
218 };
219 ProxyZoneSpec.prototype.setDelegate = function (delegateSpec) {
220 var _this = this;
221 var isNewDelegate = this._delegateSpec !== delegateSpec;
222 this._delegateSpec = delegateSpec;
223 this.propertyKeys && this.propertyKeys.forEach(function (key) { return delete _this.properties[key]; });
224 this.propertyKeys = null;
225 if (delegateSpec && delegateSpec.properties) {
226 this.propertyKeys = Object.keys(delegateSpec.properties);
227 this.propertyKeys.forEach(function (k) { return _this.properties[k] = delegateSpec.properties[k]; });
228 }
229 // if a new delegateSpec was set, check if we need to trigger hasTask
230 if (isNewDelegate && this.lastTaskState &&
231 (this.lastTaskState.macroTask || this.lastTaskState.microTask)) {
232 this.isNeedToTriggerHasTask = true;
233 }
234 };
235 ProxyZoneSpec.prototype.getDelegate = function () {
236 return this._delegateSpec;
237 };
238 ProxyZoneSpec.prototype.resetDelegate = function () {
239 var delegateSpec = this.getDelegate();
240 this.setDelegate(this.defaultSpecDelegate);
241 };
242 ProxyZoneSpec.prototype.tryTriggerHasTask = function (parentZoneDelegate, currentZone, targetZone) {
243 if (this.isNeedToTriggerHasTask && this.lastTaskState) {
244 // last delegateSpec has microTask or macroTask
245 // should call onHasTask in current delegateSpec
246 this.isNeedToTriggerHasTask = false;
247 this.onHasTask(parentZoneDelegate, currentZone, targetZone, this.lastTaskState);
248 }
249 };
250 ProxyZoneSpec.prototype.removeFromTasks = function (task) {
251 if (!this.tasks) {
252 return;
253 }
254 for (var i = 0; i < this.tasks.length; i++) {
255 if (this.tasks[i] === task) {
256 this.tasks.splice(i, 1);
257 return;
258 }
259 }
260 };
261 ProxyZoneSpec.prototype.getAndClearPendingTasksInfo = function () {
262 if (this.tasks.length === 0) {
263 return '';
264 }
265 var taskInfo = this.tasks.map(function (task) {
266 var dataInfo = task.data &&
267 Object.keys(task.data)
268 .map(function (key) {
269 return key + ':' + task.data[key];
270 })
271 .join(',');
272 return "type: " + task.type + ", source: " + task.source + ", args: {" + dataInfo + "}";
273 });
274 var pendingTasksInfo = '--Pending async tasks are: [' + taskInfo + ']';
275 // clear tasks
276 this.tasks = [];
277 return pendingTasksInfo;
278 };
279 ProxyZoneSpec.prototype.onFork = function (parentZoneDelegate, currentZone, targetZone, zoneSpec) {
280 if (this._delegateSpec && this._delegateSpec.onFork) {
281 return this._delegateSpec.onFork(parentZoneDelegate, currentZone, targetZone, zoneSpec);
282 }
283 else {
284 return parentZoneDelegate.fork(targetZone, zoneSpec);
285 }
286 };
287 ProxyZoneSpec.prototype.onIntercept = function (parentZoneDelegate, currentZone, targetZone, delegate, source) {
288 if (this._delegateSpec && this._delegateSpec.onIntercept) {
289 return this._delegateSpec.onIntercept(parentZoneDelegate, currentZone, targetZone, delegate, source);
290 }
291 else {
292 return parentZoneDelegate.intercept(targetZone, delegate, source);
293 }
294 };
295 ProxyZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
296 this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
297 if (this._delegateSpec && this._delegateSpec.onInvoke) {
298 return this._delegateSpec.onInvoke(parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source);
299 }
300 else {
301 return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
302 }
303 };
304 ProxyZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
305 if (this._delegateSpec && this._delegateSpec.onHandleError) {
306 return this._delegateSpec.onHandleError(parentZoneDelegate, currentZone, targetZone, error);
307 }
308 else {
309 return parentZoneDelegate.handleError(targetZone, error);
310 }
311 };
312 ProxyZoneSpec.prototype.onScheduleTask = function (parentZoneDelegate, currentZone, targetZone, task) {
313 if (task.type !== 'eventTask') {
314 this.tasks.push(task);
315 }
316 if (this._delegateSpec && this._delegateSpec.onScheduleTask) {
317 return this._delegateSpec.onScheduleTask(parentZoneDelegate, currentZone, targetZone, task);
318 }
319 else {
320 return parentZoneDelegate.scheduleTask(targetZone, task);
321 }
322 };
323 ProxyZoneSpec.prototype.onInvokeTask = function (parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs) {
324 if (task.type !== 'eventTask') {
325 this.removeFromTasks(task);
326 }
327 this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
328 if (this._delegateSpec && this._delegateSpec.onInvokeTask) {
329 return this._delegateSpec.onInvokeTask(parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs);
330 }
331 else {
332 return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
333 }
334 };
335 ProxyZoneSpec.prototype.onCancelTask = function (parentZoneDelegate, currentZone, targetZone, task) {
336 if (task.type !== 'eventTask') {
337 this.removeFromTasks(task);
338 }
339 this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
340 if (this._delegateSpec && this._delegateSpec.onCancelTask) {
341 return this._delegateSpec.onCancelTask(parentZoneDelegate, currentZone, targetZone, task);
342 }
343 else {
344 return parentZoneDelegate.cancelTask(targetZone, task);
345 }
346 };
347 ProxyZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
348 this.lastTaskState = hasTaskState;
349 if (this._delegateSpec && this._delegateSpec.onHasTask) {
350 this._delegateSpec.onHasTask(delegate, current, target, hasTaskState);
351 }
352 else {
353 delegate.hasTask(target, hasTaskState);
354 }
355 };
356 return ProxyZoneSpec;
357 }());
358 // Export the class so that new instances can be created with proper
359 // constructor params.
360 Zone['ProxyZoneSpec'] = ProxyZoneSpec;
361 /**
362 * @license
363 * Copyright Google LLC All Rights Reserved.
364 *
365 * Use of this source code is governed by an MIT-style license that can be
366 * found in the LICENSE file at https://angular.io/license
367 */
368 var SyncTestZoneSpec = /** @class */ (function () {
369 function SyncTestZoneSpec(namePrefix) {
370 this.runZone = Zone.current;
371 this.name = 'syncTestZone for ' + namePrefix;
372 }
373 SyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
374 switch (task.type) {
375 case 'microTask':
376 case 'macroTask':
377 throw new Error("Cannot call " + task.source + " from within a sync test.");
378 case 'eventTask':
379 task = delegate.scheduleTask(target, task);
380 break;
381 }
382 return task;
383 };
384 return SyncTestZoneSpec;
385 }());
386 // Export the class so that new instances can be created with proper
387 // constructor params.
388 Zone['SyncTestZoneSpec'] = SyncTestZoneSpec;
389 /**
390 * @license
391 * Copyright Google LLC All Rights Reserved.
392 *
393 * Use of this source code is governed by an MIT-style license that can be
394 * found in the LICENSE file at https://angular.io/license
395 */
396 Zone.__load_patch('jasmine', function (global, Zone, api) {
397 var __extends = function (d, b) {
398 for (var p in b)
399 if (b.hasOwnProperty(p))
400 d[p] = b[p];
401 function __() {
402 this.constructor = d;
403 }
404 d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __());
405 };
406 // Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
407 // in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
408 if (!Zone)
409 throw new Error('Missing: zone.js');
410 if (typeof jest !== 'undefined') {
411 // return if jasmine is a light implementation inside jest
412 // in this case, we are running inside jest not jasmine
413 return;
414 }
415 if (typeof jasmine == 'undefined' || jasmine['__zone_patch__']) {
416 return;
417 }
418 jasmine['__zone_patch__'] = true;
419 var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
420 var ProxyZoneSpec = Zone['ProxyZoneSpec'];
421 if (!SyncTestZoneSpec)
422 throw new Error('Missing: SyncTestZoneSpec');
423 if (!ProxyZoneSpec)
424 throw new Error('Missing: ProxyZoneSpec');
425 var ambientZone = Zone.current;
426 // Create a synchronous-only zone in which to run `describe` blocks in order to raise an
427 // error if any asynchronous operations are attempted inside of a `describe` but outside of
428 // a `beforeEach` or `it`.
429 var syncZone = ambientZone.fork(new SyncTestZoneSpec('jasmine.describe'));
430 var symbol = Zone.__symbol__;
431 // whether patch jasmine clock when in fakeAsync
432 var disablePatchingJasmineClock = global[symbol('fakeAsyncDisablePatchingClock')] === true;
433 // the original variable name fakeAsyncPatchLock is not accurate, so the name will be
434 // fakeAsyncAutoFakeAsyncWhenClockPatched and if this enablePatchingJasmineClock is false, we also
435 // automatically disable the auto jump into fakeAsync feature
436 var enableAutoFakeAsyncWhenClockPatched = !disablePatchingJasmineClock &&
437 ((global[symbol('fakeAsyncPatchLock')] === true) ||
438 (global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true));
439 var ignoreUnhandledRejection = global[symbol('ignoreUnhandledRejection')] === true;
440 if (!ignoreUnhandledRejection) {
441 var globalErrors_1 = jasmine.GlobalErrors;
442 if (globalErrors_1 && !jasmine[symbol('GlobalErrors')]) {
443 jasmine[symbol('GlobalErrors')] = globalErrors_1;
444 jasmine.GlobalErrors = function () {
445 var instance = new globalErrors_1();
446 var originalInstall = instance.install;
447 if (originalInstall && !instance[symbol('install')]) {
448 instance[symbol('install')] = originalInstall;
449 instance.install = function () {
450 var originalHandlers = process.listeners('unhandledRejection');
451 var r = originalInstall.apply(this, arguments);
452 process.removeAllListeners('unhandledRejection');
453 if (originalHandlers) {
454 originalHandlers.forEach(function (h) { return process.on('unhandledRejection', h); });
455 }
456 return r;
457 };
458 }
459 return instance;
460 };
461 }
462 }
463 // Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
464 var jasmineEnv = jasmine.getEnv();
465 ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
466 var originalJasmineFn = jasmineEnv[methodName];
467 jasmineEnv[methodName] = function (description, specDefinitions) {
468 return originalJasmineFn.call(this, description, wrapDescribeInZone(specDefinitions));
469 };
470 });
471 ['it', 'xit', 'fit'].forEach(function (methodName) {
472 var originalJasmineFn = jasmineEnv[methodName];
473 jasmineEnv[symbol(methodName)] = originalJasmineFn;
474 jasmineEnv[methodName] = function (description, specDefinitions, timeout) {
475 arguments[1] = wrapTestInZone(specDefinitions);
476 return originalJasmineFn.apply(this, arguments);
477 };
478 });
479 ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(function (methodName) {
480 var originalJasmineFn = jasmineEnv[methodName];
481 jasmineEnv[symbol(methodName)] = originalJasmineFn;
482 jasmineEnv[methodName] = function (specDefinitions, timeout) {
483 arguments[0] = wrapTestInZone(specDefinitions);
484 return originalJasmineFn.apply(this, arguments);
485 };
486 });
487 if (!disablePatchingJasmineClock) {
488 // need to patch jasmine.clock().mockDate and jasmine.clock().tick() so
489 // they can work properly in FakeAsyncTest
490 var originalClockFn_1 = (jasmine[symbol('clock')] = jasmine['clock']);
491 jasmine['clock'] = function () {
492 var clock = originalClockFn_1.apply(this, arguments);
493 if (!clock[symbol('patched')]) {
494 clock[symbol('patched')] = symbol('patched');
495 var originalTick_1 = (clock[symbol('tick')] = clock.tick);
496 clock.tick = function () {
497 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
498 if (fakeAsyncZoneSpec) {
499 return fakeAsyncZoneSpec.tick.apply(fakeAsyncZoneSpec, arguments);
500 }
501 return originalTick_1.apply(this, arguments);
502 };
503 var originalMockDate_1 = (clock[symbol('mockDate')] = clock.mockDate);
504 clock.mockDate = function () {
505 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
506 if (fakeAsyncZoneSpec) {
507 var dateTime = arguments.length > 0 ? arguments[0] : new Date();
508 return fakeAsyncZoneSpec.setFakeBaseSystemTime.apply(fakeAsyncZoneSpec, dateTime && typeof dateTime.getTime === 'function' ? [dateTime.getTime()] :
509 arguments);
510 }
511 return originalMockDate_1.apply(this, arguments);
512 };
513 // for auto go into fakeAsync feature, we need the flag to enable it
514 if (enableAutoFakeAsyncWhenClockPatched) {
515 ['install', 'uninstall'].forEach(function (methodName) {
516 var originalClockFn = (clock[symbol(methodName)] = clock[methodName]);
517 clock[methodName] = function () {
518 var FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec'];
519 if (FakeAsyncTestZoneSpec) {
520 jasmine[symbol('clockInstalled')] = 'install' === methodName;
521 return;
522 }
523 return originalClockFn.apply(this, arguments);
524 };
525 });
526 }
527 }
528 return clock;
529 };
530 }
531 // monkey patch createSpyObj to make properties enumerable to true
532 if (!jasmine[Zone.__symbol__('createSpyObj')]) {
533 var originalCreateSpyObj_1 = jasmine.createSpyObj;
534 jasmine[Zone.__symbol__('createSpyObj')] = originalCreateSpyObj_1;
535 jasmine.createSpyObj = function () {
536 var args = Array.prototype.slice.call(arguments);
537 var propertyNames = args.length >= 3 ? args[2] : null;
538 var spyObj;
539 if (propertyNames) {
540 var defineProperty_1 = Object.defineProperty;
541 Object.defineProperty = function (obj, p, attributes) {
542 return defineProperty_1.call(this, obj, p, Object.assign(Object.assign({}, attributes), { configurable: true, enumerable: true }));
543 };
544 try {
545 spyObj = originalCreateSpyObj_1.apply(this, args);
546 }
547 finally {
548 Object.defineProperty = defineProperty_1;
549 }
550 }
551 else {
552 spyObj = originalCreateSpyObj_1.apply(this, args);
553 }
554 return spyObj;
555 };
556 }
557 /**
558 * Gets a function wrapping the body of a Jasmine `describe` block to execute in a
559 * synchronous-only zone.
560 */
561 function wrapDescribeInZone(describeBody) {
562 return function () {
563 return syncZone.run(describeBody, this, arguments);
564 };
565 }
566 function runInTestZone(testBody, applyThis, queueRunner, done) {
567 var isClockInstalled = !!jasmine[symbol('clockInstalled')];
568 var testProxyZoneSpec = queueRunner.testProxyZoneSpec;
569 var testProxyZone = queueRunner.testProxyZone;
570 if (isClockInstalled && enableAutoFakeAsyncWhenClockPatched) {
571 // auto run a fakeAsync
572 var fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
573 if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
574 testBody = fakeAsyncModule.fakeAsync(testBody);
575 }
576 }
577 if (done) {
578 return testProxyZone.run(testBody, applyThis, [done]);
579 }
580 else {
581 return testProxyZone.run(testBody, applyThis);
582 }
583 }
584 /**
585 * Gets a function wrapping the body of a Jasmine `it/beforeEach/afterEach` block to
586 * execute in a ProxyZone zone.
587 * This will run in `testProxyZone`. The `testProxyZone` will be reset by the `ZoneQueueRunner`
588 */
589 function wrapTestInZone(testBody) {
590 // The `done` callback is only passed through if the function expects at least one argument.
591 // Note we have to make a function with correct number of arguments, otherwise jasmine will
592 // think that all functions are sync or async.
593 return (testBody && (testBody.length ? function (done) {
594 return runInTestZone(testBody, this, this.queueRunner, done);
595 } : function () {
596 return runInTestZone(testBody, this, this.queueRunner);
597 }));
598 }
599 var QueueRunner = jasmine.QueueRunner;
600 jasmine.QueueRunner = (function (_super) {
601 __extends(ZoneQueueRunner, _super);
602 function ZoneQueueRunner(attrs) {
603 var _this = this;
604 if (attrs.onComplete) {
605 attrs.onComplete = (function (fn) { return function () {
606 // All functions are done, clear the test zone.
607 _this.testProxyZone = null;
608 _this.testProxyZoneSpec = null;
609 ambientZone.scheduleMicroTask('jasmine.onComplete', fn);
610 }; })(attrs.onComplete);
611 }
612 var nativeSetTimeout = global[Zone.__symbol__('setTimeout')];
613 var nativeClearTimeout = global[Zone.__symbol__('clearTimeout')];
614 if (nativeSetTimeout) {
615 // should run setTimeout inside jasmine outside of zone
616 attrs.timeout = {
617 setTimeout: nativeSetTimeout ? nativeSetTimeout : global.setTimeout,
618 clearTimeout: nativeClearTimeout ? nativeClearTimeout : global.clearTimeout
619 };
620 }
621 // create a userContext to hold the queueRunner itself
622 // so we can access the testProxy in it/xit/beforeEach ...
623 if (jasmine.UserContext) {
624 if (!attrs.userContext) {
625 attrs.userContext = new jasmine.UserContext();
626 }
627 attrs.userContext.queueRunner = this;
628 }
629 else {
630 if (!attrs.userContext) {
631 attrs.userContext = {};
632 }
633 attrs.userContext.queueRunner = this;
634 }
635 // patch attrs.onException
636 var onException = attrs.onException;
637 attrs.onException = function (error) {
638 if (error &&
639 error.message ===
640 'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.') {
641 // jasmine timeout, we can make the error message more
642 // reasonable to tell what tasks are pending
643 var proxyZoneSpec = this && this.testProxyZoneSpec;
644 if (proxyZoneSpec) {
645 var pendingTasksInfo = proxyZoneSpec.getAndClearPendingTasksInfo();
646 try {
647 // try catch here in case error.message is not writable
648 error.message += pendingTasksInfo;
649 }
650 catch (err) {
651 }
652 }
653 }
654 if (onException) {
655 onException.call(this, error);
656 }
657 };
658 _super.call(this, attrs);
659 }
660 ZoneQueueRunner.prototype.execute = function () {
661 var _this = this;
662 var zone = Zone.current;
663 var isChildOfAmbientZone = false;
664 while (zone) {
665 if (zone === ambientZone) {
666 isChildOfAmbientZone = true;
667 break;
668 }
669 zone = zone.parent;
670 }
671 if (!isChildOfAmbientZone)
672 throw new Error('Unexpected Zone: ' + Zone.current.name);
673 // This is the zone which will be used for running individual tests.
674 // It will be a proxy zone, so that the tests function can retroactively install
675 // different zones.
676 // Example:
677 // - In beforeEach() do childZone = Zone.current.fork(...);
678 // - In it() try to do fakeAsync(). The issue is that because the beforeEach forked the
679 // zone outside of fakeAsync it will be able to escape the fakeAsync rules.
680 // - Because ProxyZone is parent fo `childZone` fakeAsync can retroactively add
681 // fakeAsync behavior to the childZone.
682 this.testProxyZoneSpec = new ProxyZoneSpec();
683 this.testProxyZone = ambientZone.fork(this.testProxyZoneSpec);
684 if (!Zone.currentTask) {
685 // if we are not running in a task then if someone would register a
686 // element.addEventListener and then calling element.click() the
687 // addEventListener callback would think that it is the top most task and would
688 // drain the microtask queue on element.click() which would be incorrect.
689 // For this reason we always force a task when running jasmine tests.
690 Zone.current.scheduleMicroTask('jasmine.execute().forceTask', function () { return QueueRunner.prototype.execute.call(_this); });
691 }
692 else {
693 _super.prototype.execute.call(this);
694 }
695 };
696 return ZoneQueueRunner;
697 })(QueueRunner);
698 });
699 /**
700 * @license
701 * Copyright Google LLC All Rights Reserved.
702 *
703 * Use of this source code is governed by an MIT-style license that can be
704 * found in the LICENSE file at https://angular.io/license
705 */
706 Zone.__load_patch('jest', function (context, Zone, api) {
707 if (typeof jest === 'undefined' || jest['__zone_patch__']) {
708 return;
709 }
710 jest['__zone_patch__'] = true;
711 var ProxyZoneSpec = Zone['ProxyZoneSpec'];
712 var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
713 if (!ProxyZoneSpec) {
714 throw new Error('Missing ProxyZoneSpec');
715 }
716 var rootZone = Zone.current;
717 var syncZone = rootZone.fork(new SyncTestZoneSpec('jest.describe'));
718 var proxyZoneSpec = new ProxyZoneSpec();
719 var proxyZone = rootZone.fork(proxyZoneSpec);
720 function wrapDescribeFactoryInZone(originalJestFn) {
721 return function () {
722 var tableArgs = [];
723 for (var _i = 0; _i < arguments.length; _i++) {
724 tableArgs[_i] = arguments[_i];
725 }
726 var originalDescribeFn = originalJestFn.apply(this, tableArgs);
727 return function () {
728 var args = [];
729 for (var _i = 0; _i < arguments.length; _i++) {
730 args[_i] = arguments[_i];
731 }
732 args[1] = wrapDescribeInZone(args[1]);
733 return originalDescribeFn.apply(this, args);
734 };
735 };
736 }
737 function wrapTestFactoryInZone(originalJestFn) {
738 return function () {
739 var tableArgs = [];
740 for (var _i = 0; _i < arguments.length; _i++) {
741 tableArgs[_i] = arguments[_i];
742 }
743 return function () {
744 var args = [];
745 for (var _i = 0; _i < arguments.length; _i++) {
746 args[_i] = arguments[_i];
747 }
748 args[1] = wrapTestInZone(args[1]);
749 return originalJestFn.apply(this, tableArgs).apply(this, args);
750 };
751 };
752 }
753 /**
754 * Gets a function wrapping the body of a jest `describe` block to execute in a
755 * synchronous-only zone.
756 */
757 function wrapDescribeInZone(describeBody) {
758 return function () {
759 var args = [];
760 for (var _i = 0; _i < arguments.length; _i++) {
761 args[_i] = arguments[_i];
762 }
763 return syncZone.run(describeBody, this, args);
764 };
765 }
766 /**
767 * Gets a function wrapping the body of a jest `it/beforeEach/afterEach` block to
768 * execute in a ProxyZone zone.
769 * This will run in the `proxyZone`.
770 */
771 function wrapTestInZone(testBody, isTestFunc) {
772 if (isTestFunc === void 0) { isTestFunc = false; }
773 if (typeof testBody !== 'function') {
774 return testBody;
775 }
776 var wrappedFunc = function () {
777 if (Zone[api.symbol('useFakeTimersCalled')] === true && testBody &&
778 !testBody.isFakeAsync) {
779 // jest.useFakeTimers is called, run into fakeAsyncTest automatically.
780 var fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
781 if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
782 testBody = fakeAsyncModule.fakeAsync(testBody);
783 }
784 }
785 proxyZoneSpec.isTestFunc = isTestFunc;
786 return proxyZone.run(testBody, null, arguments);
787 };
788 // Update the length of wrappedFunc to be the same as the length of the testBody
789 // So jest core can handle whether the test function has `done()` or not correctly
790 Object.defineProperty(wrappedFunc, 'length', { configurable: true, writable: true, enumerable: false });
791 wrappedFunc.length = testBody.length;
792 return wrappedFunc;
793 }
794 ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
795 var originalJestFn = context[methodName];
796 if (context[Zone.__symbol__(methodName)]) {
797 return;
798 }
799 context[Zone.__symbol__(methodName)] = originalJestFn;
800 context[methodName] = function () {
801 var args = [];
802 for (var _i = 0; _i < arguments.length; _i++) {
803 args[_i] = arguments[_i];
804 }
805 args[1] = wrapDescribeInZone(args[1]);
806 return originalJestFn.apply(this, args);
807 };
808 context[methodName].each = wrapDescribeFactoryInZone(originalJestFn.each);
809 });
810 context.describe.only = context.fdescribe;
811 context.describe.skip = context.xdescribe;
812 ['it', 'xit', 'fit', 'test', 'xtest'].forEach(function (methodName) {
813 var originalJestFn = context[methodName];
814 if (context[Zone.__symbol__(methodName)]) {
815 return;
816 }
817 context[Zone.__symbol__(methodName)] = originalJestFn;
818 context[methodName] = function () {
819 var args = [];
820 for (var _i = 0; _i < arguments.length; _i++) {
821 args[_i] = arguments[_i];
822 }
823 args[1] = wrapTestInZone(args[1], true);
824 return originalJestFn.apply(this, args);
825 };
826 context[methodName].each = wrapTestFactoryInZone(originalJestFn.each);
827 context[methodName].todo = originalJestFn.todo;
828 });
829 context.it.only = context.fit;
830 context.it.skip = context.xit;
831 context.test.only = context.fit;
832 context.test.skip = context.xit;
833 ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(function (methodName) {
834 var originalJestFn = context[methodName];
835 if (context[Zone.__symbol__(methodName)]) {
836 return;
837 }
838 context[Zone.__symbol__(methodName)] = originalJestFn;
839 context[methodName] = function () {
840 var args = [];
841 for (var _i = 0; _i < arguments.length; _i++) {
842 args[_i] = arguments[_i];
843 }
844 args[0] = wrapTestInZone(args[0]);
845 return originalJestFn.apply(this, args);
846 };
847 });
848 Zone.patchJestObject = function patchJestObject(Timer, isModern) {
849 if (isModern === void 0) { isModern = false; }
850 // check whether currently the test is inside fakeAsync()
851 function isPatchingFakeTimer() {
852 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
853 return !!fakeAsyncZoneSpec;
854 }
855 // check whether the current function is inside `test/it` or other methods
856 // such as `describe/beforeEach`
857 function isInTestFunc() {
858 var proxyZoneSpec = Zone.current.get('ProxyZoneSpec');
859 return proxyZoneSpec && proxyZoneSpec.isTestFunc;
860 }
861 if (Timer[api.symbol('fakeTimers')]) {
862 return;
863 }
864 Timer[api.symbol('fakeTimers')] = true;
865 // patch jest fakeTimer internal method to make sure no console.warn print out
866 api.patchMethod(Timer, '_checkFakeTimers', function (delegate) {
867 return function (self, args) {
868 if (isPatchingFakeTimer()) {
869 return true;
870 }
871 else {
872 return delegate.apply(self, args);
873 }
874 };
875 });
876 // patch useFakeTimers(), set useFakeTimersCalled flag, and make test auto run into fakeAsync
877 api.patchMethod(Timer, 'useFakeTimers', function (delegate) {
878 return function (self, args) {
879 Zone[api.symbol('useFakeTimersCalled')] = true;
880 if (isModern || isInTestFunc()) {
881 return delegate.apply(self, args);
882 }
883 return self;
884 };
885 });
886 // patch useRealTimers(), unset useFakeTimers flag
887 api.patchMethod(Timer, 'useRealTimers', function (delegate) {
888 return function (self, args) {
889 Zone[api.symbol('useFakeTimersCalled')] = false;
890 if (isModern || isInTestFunc()) {
891 return delegate.apply(self, args);
892 }
893 return self;
894 };
895 });
896 // patch setSystemTime(), call setCurrentRealTime() in the fakeAsyncTest
897 api.patchMethod(Timer, 'setSystemTime', function (delegate) {
898 return function (self, args) {
899 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
900 if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
901 fakeAsyncZoneSpec.setFakeBaseSystemTime(args[0]);
902 }
903 else {
904 return delegate.apply(self, args);
905 }
906 };
907 });
908 // patch getSystemTime(), call getCurrentRealTime() in the fakeAsyncTest
909 api.patchMethod(Timer, 'getRealSystemTime', function (delegate) {
910 return function (self, args) {
911 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
912 if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
913 return fakeAsyncZoneSpec.getRealSystemTime();
914 }
915 else {
916 return delegate.apply(self, args);
917 }
918 };
919 });
920 // patch runAllTicks(), run all microTasks inside fakeAsync
921 api.patchMethod(Timer, 'runAllTicks', function (delegate) {
922 return function (self, args) {
923 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
924 if (fakeAsyncZoneSpec) {
925 fakeAsyncZoneSpec.flushMicrotasks();
926 }
927 else {
928 return delegate.apply(self, args);
929 }
930 };
931 });
932 // patch runAllTimers(), run all macroTasks inside fakeAsync
933 api.patchMethod(Timer, 'runAllTimers', function (delegate) {
934 return function (self, args) {
935 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
936 if (fakeAsyncZoneSpec) {
937 fakeAsyncZoneSpec.flush(100, true);
938 }
939 else {
940 return delegate.apply(self, args);
941 }
942 };
943 });
944 // patch advanceTimersByTime(), call tick() in the fakeAsyncTest
945 api.patchMethod(Timer, 'advanceTimersByTime', function (delegate) {
946 return function (self, args) {
947 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
948 if (fakeAsyncZoneSpec) {
949 fakeAsyncZoneSpec.tick(args[0]);
950 }
951 else {
952 return delegate.apply(self, args);
953 }
954 };
955 });
956 // patch runOnlyPendingTimers(), call flushOnlyPendingTimers() in the fakeAsyncTest
957 api.patchMethod(Timer, 'runOnlyPendingTimers', function (delegate) {
958 return function (self, args) {
959 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
960 if (fakeAsyncZoneSpec) {
961 fakeAsyncZoneSpec.flushOnlyPendingTimers();
962 }
963 else {
964 return delegate.apply(self, args);
965 }
966 };
967 });
968 // patch advanceTimersToNextTimer(), call tickToNext() in the fakeAsyncTest
969 api.patchMethod(Timer, 'advanceTimersToNextTimer', function (delegate) {
970 return function (self, args) {
971 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
972 if (fakeAsyncZoneSpec) {
973 fakeAsyncZoneSpec.tickToNext(args[0]);
974 }
975 else {
976 return delegate.apply(self, args);
977 }
978 };
979 });
980 // patch clearAllTimers(), call removeAllTimers() in the fakeAsyncTest
981 api.patchMethod(Timer, 'clearAllTimers', function (delegate) {
982 return function (self, args) {
983 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
984 if (fakeAsyncZoneSpec) {
985 fakeAsyncZoneSpec.removeAllTimers();
986 }
987 else {
988 return delegate.apply(self, args);
989 }
990 };
991 });
992 // patch getTimerCount(), call getTimerCount() in the fakeAsyncTest
993 api.patchMethod(Timer, 'getTimerCount', function (delegate) {
994 return function (self, args) {
995 var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
996 if (fakeAsyncZoneSpec) {
997 return fakeAsyncZoneSpec.getTimerCount();
998 }
999 else {
1000 return delegate.apply(self, args);
1001 }
1002 };
1003 });
1004 };
1005 });
1006 /**
1007 * @license
1008 * Copyright Google LLC All Rights Reserved.
1009 *
1010 * Use of this source code is governed by an MIT-style license that can be
1011 * found in the LICENSE file at https://angular.io/license
1012 */
1013 Zone.__load_patch('mocha', function (global, Zone) {
1014 var Mocha = global.Mocha;
1015 if (typeof Mocha === 'undefined') {
1016 // return if Mocha is not available, because now zone-testing
1017 // will load mocha patch with jasmine/jest patch
1018 return;
1019 }
1020 if (typeof Zone === 'undefined') {
1021 throw new Error('Missing Zone.js');
1022 }
1023 var ProxyZoneSpec = Zone['ProxyZoneSpec'];
1024 var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
1025 if (!ProxyZoneSpec) {
1026 throw new Error('Missing ProxyZoneSpec');
1027 }
1028 if (Mocha['__zone_patch__']) {
1029 throw new Error('"Mocha" has already been patched with "Zone".');
1030 }
1031 Mocha['__zone_patch__'] = true;
1032 var rootZone = Zone.current;
1033 var syncZone = rootZone.fork(new SyncTestZoneSpec('Mocha.describe'));
1034 var testZone = null;
1035 var suiteZone = rootZone.fork(new ProxyZoneSpec());
1036 var mochaOriginal = {
1037 after: Mocha.after,
1038 afterEach: Mocha.afterEach,
1039 before: Mocha.before,
1040 beforeEach: Mocha.beforeEach,
1041 describe: Mocha.describe,
1042 it: Mocha.it
1043 };
1044 function modifyArguments(args, syncTest, asyncTest) {
1045 var _loop_1 = function (i) {
1046 var arg = args[i];
1047 if (typeof arg === 'function') {
1048 // The `done` callback is only passed through if the function expects at
1049 // least one argument.
1050 // Note we have to make a function with correct number of arguments,
1051 // otherwise mocha will
1052 // think that all functions are sync or async.
1053 args[i] = (arg.length === 0) ? syncTest(arg) : asyncTest(arg);
1054 // Mocha uses toString to view the test body in the result list, make sure we return the
1055 // correct function body
1056 args[i].toString = function () {
1057 return arg.toString();
1058 };
1059 }
1060 };
1061 for (var i = 0; i < args.length; i++) {
1062 _loop_1(i);
1063 }
1064 return args;
1065 }
1066 function wrapDescribeInZone(args) {
1067 var syncTest = function (fn) {
1068 return function () {
1069 return syncZone.run(fn, this, arguments);
1070 };
1071 };
1072 return modifyArguments(args, syncTest);
1073 }
1074 function wrapTestInZone(args) {
1075 var asyncTest = function (fn) {
1076 return function (done) {
1077 return testZone.run(fn, this, [done]);
1078 };
1079 };
1080 var syncTest = function (fn) {
1081 return function () {
1082 return testZone.run(fn, this);
1083 };
1084 };
1085 return modifyArguments(args, syncTest, asyncTest);
1086 }
1087 function wrapSuiteInZone(args) {
1088 var asyncTest = function (fn) {
1089 return function (done) {
1090 return suiteZone.run(fn, this, [done]);
1091 };
1092 };
1093 var syncTest = function (fn) {
1094 return function () {
1095 return suiteZone.run(fn, this);
1096 };
1097 };
1098 return modifyArguments(args, syncTest, asyncTest);
1099 }
1100 global.describe = global.suite = Mocha.describe = function () {
1101 return mochaOriginal.describe.apply(this, wrapDescribeInZone(arguments));
1102 };
1103 global.xdescribe = global.suite.skip = Mocha.describe.skip = function () {
1104 return mochaOriginal.describe.skip.apply(this, wrapDescribeInZone(arguments));
1105 };
1106 global.describe.only = global.suite.only = Mocha.describe.only = function () {
1107 return mochaOriginal.describe.only.apply(this, wrapDescribeInZone(arguments));
1108 };
1109 global.it = global.specify = global.test = Mocha.it = function () {
1110 return mochaOriginal.it.apply(this, wrapTestInZone(arguments));
1111 };
1112 global.xit = global.xspecify = Mocha.it.skip = function () {
1113 return mochaOriginal.it.skip.apply(this, wrapTestInZone(arguments));
1114 };
1115 global.it.only = global.test.only = Mocha.it.only = function () {
1116 return mochaOriginal.it.only.apply(this, wrapTestInZone(arguments));
1117 };
1118 global.after = global.suiteTeardown = Mocha.after = function () {
1119 return mochaOriginal.after.apply(this, wrapSuiteInZone(arguments));
1120 };
1121 global.afterEach = global.teardown = Mocha.afterEach = function () {
1122 return mochaOriginal.afterEach.apply(this, wrapTestInZone(arguments));
1123 };
1124 global.before = global.suiteSetup = Mocha.before = function () {
1125 return mochaOriginal.before.apply(this, wrapSuiteInZone(arguments));
1126 };
1127 global.beforeEach = global.setup = Mocha.beforeEach = function () {
1128 return mochaOriginal.beforeEach.apply(this, wrapTestInZone(arguments));
1129 };
1130 (function (originalRunTest, originalRun) {
1131 Mocha.Runner.prototype.runTest = function (fn) {
1132 var _this = this;
1133 Zone.current.scheduleMicroTask('mocha.forceTask', function () {
1134 originalRunTest.call(_this, fn);
1135 });
1136 };
1137 Mocha.Runner.prototype.run = function (fn) {
1138 this.on('test', function (e) {
1139 testZone = rootZone.fork(new ProxyZoneSpec());
1140 });
1141 this.on('fail', function (test, err) {
1142 var proxyZoneSpec = testZone && testZone.get('ProxyZoneSpec');
1143 if (proxyZoneSpec && err) {
1144 try {
1145 // try catch here in case err.message is not writable
1146 err.message += proxyZoneSpec.getAndClearPendingTasksInfo();
1147 }
1148 catch (error) {
1149 }
1150 }
1151 });
1152 return originalRun.call(this, fn);
1153 };
1154 })(Mocha.Runner.prototype.runTest, Mocha.Runner.prototype.run);
1155 });
1156 /**
1157 * @license
1158 * Copyright Google LLC All Rights Reserved.
1159 *
1160 * Use of this source code is governed by an MIT-style license that can be
1161 * found in the LICENSE file at https://angular.io/license
1162 */
1163 (function (_global) {
1164 var AsyncTestZoneSpec = /** @class */ (function () {
1165 function AsyncTestZoneSpec(finishCallback, failCallback, namePrefix) {
1166 this.finishCallback = finishCallback;
1167 this.failCallback = failCallback;
1168 this._pendingMicroTasks = false;
1169 this._pendingMacroTasks = false;
1170 this._alreadyErrored = false;
1171 this._isSync = false;
1172 this.runZone = Zone.current;
1173 this.unresolvedChainedPromiseCount = 0;
1174 this.supportWaitUnresolvedChainedPromise = false;
1175 this.name = 'asyncTestZone for ' + namePrefix;
1176 this.properties = { 'AsyncTestZoneSpec': this };
1177 this.supportWaitUnresolvedChainedPromise =
1178 _global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] === true;
1179 }
1180 AsyncTestZoneSpec.prototype.isUnresolvedChainedPromisePending = function () {
1181 return this.unresolvedChainedPromiseCount > 0;
1182 };
1183 AsyncTestZoneSpec.prototype._finishCallbackIfDone = function () {
1184 var _this = this;
1185 if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
1186 (this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending()))) {
1187 // We do this because we would like to catch unhandled rejected promises.
1188 this.runZone.run(function () {
1189 setTimeout(function () {
1190 if (!_this._alreadyErrored && !(_this._pendingMicroTasks || _this._pendingMacroTasks)) {
1191 _this.finishCallback();
1192 }
1193 }, 0);
1194 });
1195 }
1196 };
1197 AsyncTestZoneSpec.prototype.patchPromiseForTest = function () {
1198 if (!this.supportWaitUnresolvedChainedPromise) {
1199 return;
1200 }
1201 var patchPromiseForTest = Promise[Zone.__symbol__('patchPromiseForTest')];
1202 if (patchPromiseForTest) {
1203 patchPromiseForTest();
1204 }
1205 };
1206 AsyncTestZoneSpec.prototype.unPatchPromiseForTest = function () {
1207 if (!this.supportWaitUnresolvedChainedPromise) {
1208 return;
1209 }
1210 var unPatchPromiseForTest = Promise[Zone.__symbol__('unPatchPromiseForTest')];
1211 if (unPatchPromiseForTest) {
1212 unPatchPromiseForTest();
1213 }
1214 };
1215 AsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
1216 if (task.type !== 'eventTask') {
1217 this._isSync = false;
1218 }
1219 if (task.type === 'microTask' && task.data && task.data instanceof Promise) {
1220 // check whether the promise is a chained promise
1221 if (task.data[AsyncTestZoneSpec.symbolParentUnresolved] === true) {
1222 // chained promise is being scheduled
1223 this.unresolvedChainedPromiseCount--;
1224 }
1225 }
1226 return delegate.scheduleTask(target, task);
1227 };
1228 AsyncTestZoneSpec.prototype.onInvokeTask = function (delegate, current, target, task, applyThis, applyArgs) {
1229 if (task.type !== 'eventTask') {
1230 this._isSync = false;
1231 }
1232 return delegate.invokeTask(target, task, applyThis, applyArgs);
1233 };
1234 AsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
1235 if (task.type !== 'eventTask') {
1236 this._isSync = false;
1237 }
1238 return delegate.cancelTask(target, task);
1239 };
1240 // Note - we need to use onInvoke at the moment to call finish when a test is
1241 // fully synchronous. TODO(juliemr): remove this when the logic for
1242 // onHasTask changes and it calls whenever the task queues are dirty.
1243 // updated by(JiaLiPassion), only call finish callback when no task
1244 // was scheduled/invoked/canceled.
1245 AsyncTestZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
1246 try {
1247 this._isSync = true;
1248 return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
1249 }
1250 finally {
1251 var afterTaskCounts = parentZoneDelegate._taskCounts;
1252 if (this._isSync) {
1253 this._finishCallbackIfDone();
1254 }
1255 }
1256 };
1257 AsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
1258 // Let the parent try to handle the error.
1259 var result = parentZoneDelegate.handleError(targetZone, error);
1260 if (result) {
1261 this.failCallback(error);
1262 this._alreadyErrored = true;
1263 }
1264 return false;
1265 };
1266 AsyncTestZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
1267 delegate.hasTask(target, hasTaskState);
1268 if (hasTaskState.change == 'microTask') {
1269 this._pendingMicroTasks = hasTaskState.microTask;
1270 this._finishCallbackIfDone();
1271 }
1272 else if (hasTaskState.change == 'macroTask') {
1273 this._pendingMacroTasks = hasTaskState.macroTask;
1274 this._finishCallbackIfDone();
1275 }
1276 };
1277 return AsyncTestZoneSpec;
1278 }());
1279 AsyncTestZoneSpec.symbolParentUnresolved = Zone.__symbol__('parentUnresolved');
1280 // Export the class so that new instances can be created with proper
1281 // constructor params.
1282 Zone['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
1283 })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
1284 Zone.__load_patch('asynctest', function (global, Zone, api) {
1285 /**
1286 * Wraps a test function in an asynchronous test zone. The test will automatically
1287 * complete when all asynchronous calls within this zone are done.
1288 */
1289 Zone[api.symbol('asyncTest')] = function asyncTest(fn) {
1290 // If we're running using the Jasmine test framework, adapt to call the 'done'
1291 // function when asynchronous activity is finished.
1292 if (global.jasmine) {
1293 // Not using an arrow function to preserve context passed from call site
1294 return function (done) {
1295 if (!done) {
1296 // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
1297 // fake it here and assume sync.
1298 done = function () { };
1299 done.fail = function (e) {
1300 throw e;
1301 };
1302 }
1303 runInTestZone(fn, this, done, function (err) {
1304 if (typeof err === 'string') {
1305 return done.fail(new Error(err));
1306 }
1307 else {
1308 done.fail(err);
1309 }
1310 });
1311 };
1312 }
1313 // Otherwise, return a promise which will resolve when asynchronous activity
1314 // is finished. This will be correctly consumed by the Mocha framework with
1315 // it('...', async(myFn)); or can be used in a custom framework.
1316 // Not using an arrow function to preserve context passed from call site
1317 return function () {
1318 var _this = this;
1319 return new Promise(function (finishCallback, failCallback) {
1320 runInTestZone(fn, _this, finishCallback, failCallback);
1321 });
1322 };
1323 };
1324 function runInTestZone(fn, context, finishCallback, failCallback) {
1325 var currentZone = Zone.current;
1326 var AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
1327 if (AsyncTestZoneSpec === undefined) {
1328 throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
1329 'Please make sure that your environment includes zone.js/dist/async-test.js');
1330 }
1331 var ProxyZoneSpec = Zone['ProxyZoneSpec'];
1332 if (!ProxyZoneSpec) {
1333 throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
1334 'Please make sure that your environment includes zone.js/dist/proxy.js');
1335 }
1336 var proxyZoneSpec = ProxyZoneSpec.get();
1337 ProxyZoneSpec.assertPresent();
1338 // We need to create the AsyncTestZoneSpec outside the ProxyZone.
1339 // If we do it in ProxyZone then we will get to infinite recursion.
1340 var proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
1341 var previousDelegate = proxyZoneSpec.getDelegate();
1342 proxyZone.parent.run(function () {
1343 var testZoneSpec = new AsyncTestZoneSpec(function () {
1344 // Need to restore the original zone.
1345 if (proxyZoneSpec.getDelegate() == testZoneSpec) {
1346 // Only reset the zone spec if it's
1347 // sill this one. Otherwise, assume
1348 // it's OK.
1349 proxyZoneSpec.setDelegate(previousDelegate);
1350 }
1351 testZoneSpec.unPatchPromiseForTest();
1352 currentZone.run(function () {
1353 finishCallback();
1354 });
1355 }, function (error) {
1356 // Need to restore the original zone.
1357 if (proxyZoneSpec.getDelegate() == testZoneSpec) {
1358 // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
1359 proxyZoneSpec.setDelegate(previousDelegate);
1360 }
1361 testZoneSpec.unPatchPromiseForTest();
1362 currentZone.run(function () {
1363 failCallback(error);
1364 });
1365 }, 'test');
1366 proxyZoneSpec.setDelegate(testZoneSpec);
1367 testZoneSpec.patchPromiseForTest();
1368 });
1369 return Zone.current.runGuarded(fn, context);
1370 }
1371 });
1372 /**
1373 * @license
1374 * Copyright Google LLC All Rights Reserved.
1375 *
1376 * Use of this source code is governed by an MIT-style license that can be
1377 * found in the LICENSE file at https://angular.io/license
1378 */
1379 (function (global) {
1380 var OriginalDate = global.Date;
1381 // Since when we compile this file to `es2015`, and if we define
1382 // this `FakeDate` as `class FakeDate`, and then set `FakeDate.prototype`
1383 // there will be an error which is `Cannot assign to read only property 'prototype'`
1384 // so we need to use function implementation here.
1385 function FakeDate() {
1386 if (arguments.length === 0) {
1387 var d = new OriginalDate();
1388 d.setTime(FakeDate.now());
1389 return d;
1390 }
1391 else {
1392 var args = Array.prototype.slice.call(arguments);
1393 return new (OriginalDate.bind.apply(OriginalDate, __spreadArrays([void 0], args)))();
1394 }
1395 }
1396 FakeDate.now = function () {
1397 var fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
1398 if (fakeAsyncTestZoneSpec) {
1399 return fakeAsyncTestZoneSpec.getFakeSystemTime();
1400 }
1401 return OriginalDate.now.apply(this, arguments);
1402 };
1403 FakeDate.UTC = OriginalDate.UTC;
1404 FakeDate.parse = OriginalDate.parse;
1405 // keep a reference for zone patched timer function
1406 var timers = {
1407 setTimeout: global.setTimeout,
1408 setInterval: global.setInterval,
1409 clearTimeout: global.clearTimeout,
1410 clearInterval: global.clearInterval
1411 };
1412 var Scheduler = /** @class */ (function () {
1413 function Scheduler() {
1414 // Scheduler queue with the tuple of end time and callback function - sorted by end time.
1415 this._schedulerQueue = [];
1416 // Current simulated time in millis.
1417 this._currentTickTime = 0;
1418 // Current fake system base time in millis.
1419 this._currentFakeBaseSystemTime = OriginalDate.now();
1420 // track requeuePeriodicTimer
1421 this._currentTickRequeuePeriodicEntries = [];
1422 }
1423 Scheduler.prototype.getCurrentTickTime = function () {
1424 return this._currentTickTime;
1425 };
1426 Scheduler.prototype.getFakeSystemTime = function () {
1427 return this._currentFakeBaseSystemTime + this._currentTickTime;
1428 };
1429 Scheduler.prototype.setFakeBaseSystemTime = function (fakeBaseSystemTime) {
1430 this._currentFakeBaseSystemTime = fakeBaseSystemTime;
1431 };
1432 Scheduler.prototype.getRealSystemTime = function () {
1433 return OriginalDate.now();
1434 };
1435 Scheduler.prototype.scheduleFunction = function (cb, delay, options) {
1436 options = Object.assign({
1437 args: [],
1438 isPeriodic: false,
1439 isRequestAnimationFrame: false,
1440 id: -1,
1441 isRequeuePeriodic: false
1442 }, options);
1443 var currentId = options.id < 0 ? Scheduler.nextId++ : options.id;
1444 var endTime = this._currentTickTime + delay;
1445 // Insert so that scheduler queue remains sorted by end time.
1446 var newEntry = {
1447 endTime: endTime,
1448 id: currentId,
1449 func: cb,
1450 args: options.args,
1451 delay: delay,
1452 isPeriodic: options.isPeriodic,
1453 isRequestAnimationFrame: options.isRequestAnimationFrame
1454 };
1455 if (options.isRequeuePeriodic) {
1456 this._currentTickRequeuePeriodicEntries.push(newEntry);
1457 }
1458 var i = 0;
1459 for (; i < this._schedulerQueue.length; i++) {
1460 var currentEntry = this._schedulerQueue[i];
1461 if (newEntry.endTime < currentEntry.endTime) {
1462 break;
1463 }
1464 }
1465 this._schedulerQueue.splice(i, 0, newEntry);
1466 return currentId;
1467 };
1468 Scheduler.prototype.removeScheduledFunctionWithId = function (id) {
1469 for (var i = 0; i < this._schedulerQueue.length; i++) {
1470 if (this._schedulerQueue[i].id == id) {
1471 this._schedulerQueue.splice(i, 1);
1472 break;
1473 }
1474 }
1475 };
1476 Scheduler.prototype.removeAll = function () {
1477 this._schedulerQueue = [];
1478 };
1479 Scheduler.prototype.getTimerCount = function () {
1480 return this._schedulerQueue.length;
1481 };
1482 Scheduler.prototype.tickToNext = function (step, doTick, tickOptions) {
1483 if (step === void 0) { step = 1; }
1484 if (this._schedulerQueue.length < step) {
1485 return;
1486 }
1487 // Find the last task currently queued in the scheduler queue and tick
1488 // till that time.
1489 var startTime = this._currentTickTime;
1490 var targetTask = this._schedulerQueue[step - 1];
1491 this.tick(targetTask.endTime - startTime, doTick, tickOptions);
1492 };
1493 Scheduler.prototype.tick = function (millis, doTick, tickOptions) {
1494 if (millis === void 0) { millis = 0; }
1495 var finalTime = this._currentTickTime + millis;
1496 var lastCurrentTime = 0;
1497 tickOptions = Object.assign({ processNewMacroTasksSynchronously: true }, tickOptions);
1498 // we need to copy the schedulerQueue so nested timeout
1499 // will not be wrongly called in the current tick
1500 // https://github.com/angular/angular/issues/33799
1501 var schedulerQueue = tickOptions.processNewMacroTasksSynchronously ?
1502 this._schedulerQueue :
1503 this._schedulerQueue.slice();
1504 if (schedulerQueue.length === 0 && doTick) {
1505 doTick(millis);
1506 return;
1507 }
1508 while (schedulerQueue.length > 0) {
1509 // clear requeueEntries before each loop
1510 this._currentTickRequeuePeriodicEntries = [];
1511 var current = schedulerQueue[0];
1512 if (finalTime < current.endTime) {
1513 // Done processing the queue since it's sorted by endTime.
1514 break;
1515 }
1516 else {
1517 // Time to run scheduled function. Remove it from the head of queue.
1518 var current_1 = schedulerQueue.shift();
1519 if (!tickOptions.processNewMacroTasksSynchronously) {
1520 var idx = this._schedulerQueue.indexOf(current_1);
1521 if (idx >= 0) {
1522 this._schedulerQueue.splice(idx, 1);
1523 }
1524 }
1525 lastCurrentTime = this._currentTickTime;
1526 this._currentTickTime = current_1.endTime;
1527 if (doTick) {
1528 doTick(this._currentTickTime - lastCurrentTime);
1529 }
1530 var retval = current_1.func.apply(global, current_1.isRequestAnimationFrame ? [this._currentTickTime] : current_1.args);
1531 if (!retval) {
1532 // Uncaught exception in the current scheduled function. Stop processing the queue.
1533 break;
1534 }
1535 // check is there any requeue periodic entry is added in
1536 // current loop, if there is, we need to add to current loop
1537 if (!tickOptions.processNewMacroTasksSynchronously) {
1538 this._currentTickRequeuePeriodicEntries.forEach(function (newEntry) {
1539 var i = 0;
1540 for (; i < schedulerQueue.length; i++) {
1541 var currentEntry = schedulerQueue[i];
1542 if (newEntry.endTime < currentEntry.endTime) {
1543 break;
1544 }
1545 }
1546 schedulerQueue.splice(i, 0, newEntry);
1547 });
1548 }
1549 }
1550 }
1551 lastCurrentTime = this._currentTickTime;
1552 this._currentTickTime = finalTime;
1553 if (doTick) {
1554 doTick(this._currentTickTime - lastCurrentTime);
1555 }
1556 };
1557 Scheduler.prototype.flushOnlyPendingTimers = function (doTick) {
1558 if (this._schedulerQueue.length === 0) {
1559 return 0;
1560 }
1561 // Find the last task currently queued in the scheduler queue and tick
1562 // till that time.
1563 var startTime = this._currentTickTime;
1564 var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
1565 this.tick(lastTask.endTime - startTime, doTick, { processNewMacroTasksSynchronously: false });
1566 return this._currentTickTime - startTime;
1567 };
1568 Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
1569 if (limit === void 0) { limit = 20; }
1570 if (flushPeriodic === void 0) { flushPeriodic = false; }
1571 if (flushPeriodic) {
1572 return this.flushPeriodic(doTick);
1573 }
1574 else {
1575 return this.flushNonPeriodic(limit, doTick);
1576 }
1577 };
1578 Scheduler.prototype.flushPeriodic = function (doTick) {
1579 if (this._schedulerQueue.length === 0) {
1580 return 0;
1581 }
1582 // Find the last task currently queued in the scheduler queue and tick
1583 // till that time.
1584 var startTime = this._currentTickTime;
1585 var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
1586 this.tick(lastTask.endTime - startTime, doTick);
1587 return this._currentTickTime - startTime;
1588 };
1589 Scheduler.prototype.flushNonPeriodic = function (limit, doTick) {
1590 var startTime = this._currentTickTime;
1591 var lastCurrentTime = 0;
1592 var count = 0;
1593 while (this._schedulerQueue.length > 0) {
1594 count++;
1595 if (count > limit) {
1596 throw new Error('flush failed after reaching the limit of ' + limit +
1597 ' tasks. Does your code use a polling timeout?');
1598 }
1599 // flush only non-periodic timers.
1600 // If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
1601 if (this._schedulerQueue.filter(function (task) { return !task.isPeriodic && !task.isRequestAnimationFrame; })
1602 .length === 0) {
1603 break;
1604 }
1605 var current = this._schedulerQueue.shift();
1606 lastCurrentTime = this._currentTickTime;
1607 this._currentTickTime = current.endTime;
1608 if (doTick) {
1609 // Update any secondary schedulers like Jasmine mock Date.
1610 doTick(this._currentTickTime - lastCurrentTime);
1611 }
1612 var retval = current.func.apply(global, current.args);
1613 if (!retval) {
1614 // Uncaught exception in the current scheduled function. Stop processing the queue.
1615 break;
1616 }
1617 }
1618 return this._currentTickTime - startTime;
1619 };
1620 return Scheduler;
1621 }());
1622 // Next scheduler id.
1623 Scheduler.nextId = 1;
1624 var FakeAsyncTestZoneSpec = /** @class */ (function () {
1625 function FakeAsyncTestZoneSpec(namePrefix, trackPendingRequestAnimationFrame, macroTaskOptions) {
1626 if (trackPendingRequestAnimationFrame === void 0) { trackPendingRequestAnimationFrame = false; }
1627 this.trackPendingRequestAnimationFrame = trackPendingRequestAnimationFrame;
1628 this.macroTaskOptions = macroTaskOptions;
1629 this._scheduler = new Scheduler();
1630 this._microtasks = [];
1631 this._lastError = null;
1632 this._uncaughtPromiseErrors = Promise[Zone.__symbol__('uncaughtPromiseErrors')];
1633 this.pendingPeriodicTimers = [];
1634 this.pendingTimers = [];
1635 this.patchDateLocked = false;
1636 this.properties = { 'FakeAsyncTestZoneSpec': this };
1637 this.name = 'fakeAsyncTestZone for ' + namePrefix;
1638 // in case user can't access the construction of FakeAsyncTestSpec
1639 // user can also define macroTaskOptions by define a global variable.
1640 if (!this.macroTaskOptions) {
1641 this.macroTaskOptions = global[Zone.__symbol__('FakeAsyncTestMacroTask')];
1642 }
1643 }
1644 FakeAsyncTestZoneSpec.assertInZone = function () {
1645 if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
1646 throw new Error('The code should be running in the fakeAsync zone to call this function');
1647 }
1648 };
1649 FakeAsyncTestZoneSpec.prototype._fnAndFlush = function (fn, completers) {
1650 var _this = this;
1651 return function () {
1652 var args = [];
1653 for (var _i = 0; _i < arguments.length; _i++) {
1654 args[_i] = arguments[_i];
1655 }
1656 fn.apply(global, args);
1657 if (_this._lastError === null) { // Success
1658 if (completers.onSuccess != null) {
1659 completers.onSuccess.apply(global);
1660 }
1661 // Flush microtasks only on success.
1662 _this.flushMicrotasks();
1663 }
1664 else { // Failure
1665 if (completers.onError != null) {
1666 completers.onError.apply(global);
1667 }
1668 }
1669 // Return true if there were no errors, false otherwise.
1670 return _this._lastError === null;
1671 };
1672 };
1673 FakeAsyncTestZoneSpec._removeTimer = function (timers, id) {
1674 var index = timers.indexOf(id);
1675 if (index > -1) {
1676 timers.splice(index, 1);
1677 }
1678 };
1679 FakeAsyncTestZoneSpec.prototype._dequeueTimer = function (id) {
1680 var _this = this;
1681 return function () {
1682 FakeAsyncTestZoneSpec._removeTimer(_this.pendingTimers, id);
1683 };
1684 };
1685 FakeAsyncTestZoneSpec.prototype._requeuePeriodicTimer = function (fn, interval, args, id) {
1686 var _this = this;
1687 return function () {
1688 // Requeue the timer callback if it's not been canceled.
1689 if (_this.pendingPeriodicTimers.indexOf(id) !== -1) {
1690 _this._scheduler.scheduleFunction(fn, interval, { args: args, isPeriodic: true, id: id, isRequeuePeriodic: true });
1691 }
1692 };
1693 };
1694 FakeAsyncTestZoneSpec.prototype._dequeuePeriodicTimer = function (id) {
1695 var _this = this;
1696 return function () {
1697 FakeAsyncTestZoneSpec._removeTimer(_this.pendingPeriodicTimers, id);
1698 };
1699 };
1700 FakeAsyncTestZoneSpec.prototype._setTimeout = function (fn, delay, args, isTimer) {
1701 if (isTimer === void 0) { isTimer = true; }
1702 var removeTimerFn = this._dequeueTimer(Scheduler.nextId);
1703 // Queue the callback and dequeue the timer on success and error.
1704 var cb = this._fnAndFlush(fn, { onSuccess: removeTimerFn, onError: removeTimerFn });
1705 var id = this._scheduler.scheduleFunction(cb, delay, { args: args, isRequestAnimationFrame: !isTimer });
1706 if (isTimer) {
1707 this.pendingTimers.push(id);
1708 }
1709 return id;
1710 };
1711 FakeAsyncTestZoneSpec.prototype._clearTimeout = function (id) {
1712 FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
1713 this._scheduler.removeScheduledFunctionWithId(id);
1714 };
1715 FakeAsyncTestZoneSpec.prototype._setInterval = function (fn, interval, args) {
1716 var id = Scheduler.nextId;
1717 var completers = { onSuccess: null, onError: this._dequeuePeriodicTimer(id) };
1718 var cb = this._fnAndFlush(fn, completers);
1719 // Use the callback created above to requeue on success.
1720 completers.onSuccess = this._requeuePeriodicTimer(cb, interval, args, id);
1721 // Queue the callback and dequeue the periodic timer only on error.
1722 this._scheduler.scheduleFunction(cb, interval, { args: args, isPeriodic: true });
1723 this.pendingPeriodicTimers.push(id);
1724 return id;
1725 };
1726 FakeAsyncTestZoneSpec.prototype._clearInterval = function (id) {
1727 FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
1728 this._scheduler.removeScheduledFunctionWithId(id);
1729 };
1730 FakeAsyncTestZoneSpec.prototype._resetLastErrorAndThrow = function () {
1731 var error = this._lastError || this._uncaughtPromiseErrors[0];
1732 this._uncaughtPromiseErrors.length = 0;
1733 this._lastError = null;
1734 throw error;
1735 };
1736 FakeAsyncTestZoneSpec.prototype.getCurrentTickTime = function () {
1737 return this._scheduler.getCurrentTickTime();
1738 };
1739 FakeAsyncTestZoneSpec.prototype.getFakeSystemTime = function () {
1740 return this._scheduler.getFakeSystemTime();
1741 };
1742 FakeAsyncTestZoneSpec.prototype.setFakeBaseSystemTime = function (realTime) {
1743 this._scheduler.setFakeBaseSystemTime(realTime);
1744 };
1745 FakeAsyncTestZoneSpec.prototype.getRealSystemTime = function () {
1746 return this._scheduler.getRealSystemTime();
1747 };
1748 FakeAsyncTestZoneSpec.patchDate = function () {
1749 if (!!global[Zone.__symbol__('disableDatePatching')]) {
1750 // we don't want to patch global Date
1751 // because in some case, global Date
1752 // is already being patched, we need to provide
1753 // an option to let user still use their
1754 // own version of Date.
1755 return;
1756 }
1757 if (global['Date'] === FakeDate) {
1758 // already patched
1759 return;
1760 }
1761 global['Date'] = FakeDate;
1762 FakeDate.prototype = OriginalDate.prototype;
1763 // try check and reset timers
1764 // because jasmine.clock().install() may
1765 // have replaced the global timer
1766 FakeAsyncTestZoneSpec.checkTimerPatch();
1767 };
1768 FakeAsyncTestZoneSpec.resetDate = function () {
1769 if (global['Date'] === FakeDate) {
1770 global['Date'] = OriginalDate;
1771 }
1772 };
1773 FakeAsyncTestZoneSpec.checkTimerPatch = function () {
1774 if (global.setTimeout !== timers.setTimeout) {
1775 global.setTimeout = timers.setTimeout;
1776 global.clearTimeout = timers.clearTimeout;
1777 }
1778 if (global.setInterval !== timers.setInterval) {
1779 global.setInterval = timers.setInterval;
1780 global.clearInterval = timers.clearInterval;
1781 }
1782 };
1783 FakeAsyncTestZoneSpec.prototype.lockDatePatch = function () {
1784 this.patchDateLocked = true;
1785 FakeAsyncTestZoneSpec.patchDate();
1786 };
1787 FakeAsyncTestZoneSpec.prototype.unlockDatePatch = function () {
1788 this.patchDateLocked = false;
1789 FakeAsyncTestZoneSpec.resetDate();
1790 };
1791 FakeAsyncTestZoneSpec.prototype.tickToNext = function (steps, doTick, tickOptions) {
1792 if (steps === void 0) { steps = 1; }
1793 if (tickOptions === void 0) { tickOptions = { processNewMacroTasksSynchronously: true }; }
1794 if (steps <= 0) {
1795 return;
1796 }
1797 FakeAsyncTestZoneSpec.assertInZone();
1798 this.flushMicrotasks();
1799 this._scheduler.tickToNext(steps, doTick, tickOptions);
1800 if (this._lastError !== null) {
1801 this._resetLastErrorAndThrow();
1802 }
1803 };
1804 FakeAsyncTestZoneSpec.prototype.tick = function (millis, doTick, tickOptions) {
1805 if (millis === void 0) { millis = 0; }
1806 if (tickOptions === void 0) { tickOptions = { processNewMacroTasksSynchronously: true }; }
1807 FakeAsyncTestZoneSpec.assertInZone();
1808 this.flushMicrotasks();
1809 this._scheduler.tick(millis, doTick, tickOptions);
1810 if (this._lastError !== null) {
1811 this._resetLastErrorAndThrow();
1812 }
1813 };
1814 FakeAsyncTestZoneSpec.prototype.flushMicrotasks = function () {
1815 var _this = this;
1816 FakeAsyncTestZoneSpec.assertInZone();
1817 var flushErrors = function () {
1818 if (_this._lastError !== null || _this._uncaughtPromiseErrors.length) {
1819 // If there is an error stop processing the microtask queue and rethrow the error.
1820 _this._resetLastErrorAndThrow();
1821 }
1822 };
1823 while (this._microtasks.length > 0) {
1824 var microtask = this._microtasks.shift();
1825 microtask.func.apply(microtask.target, microtask.args);
1826 }
1827 flushErrors();
1828 };
1829 FakeAsyncTestZoneSpec.prototype.flush = function (limit, flushPeriodic, doTick) {
1830 FakeAsyncTestZoneSpec.assertInZone();
1831 this.flushMicrotasks();
1832 var elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
1833 if (this._lastError !== null) {
1834 this._resetLastErrorAndThrow();
1835 }
1836 return elapsed;
1837 };
1838 FakeAsyncTestZoneSpec.prototype.flushOnlyPendingTimers = function (doTick) {
1839 FakeAsyncTestZoneSpec.assertInZone();
1840 this.flushMicrotasks();
1841 var elapsed = this._scheduler.flushOnlyPendingTimers(doTick);
1842 if (this._lastError !== null) {
1843 this._resetLastErrorAndThrow();
1844 }
1845 return elapsed;
1846 };
1847 FakeAsyncTestZoneSpec.prototype.removeAllTimers = function () {
1848 FakeAsyncTestZoneSpec.assertInZone();
1849 this._scheduler.removeAll();
1850 this.pendingPeriodicTimers = [];
1851 this.pendingTimers = [];
1852 };
1853 FakeAsyncTestZoneSpec.prototype.getTimerCount = function () {
1854 return this._scheduler.getTimerCount() + this._microtasks.length;
1855 };
1856 FakeAsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
1857 switch (task.type) {
1858 case 'microTask':
1859 var args = task.data && task.data.args;
1860 // should pass additional arguments to callback if have any
1861 // currently we know process.nextTick will have such additional
1862 // arguments
1863 var additionalArgs = void 0;
1864 if (args) {
1865 var callbackIndex = task.data.cbIdx;
1866 if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
1867 additionalArgs = Array.prototype.slice.call(args, callbackIndex + 1);
1868 }
1869 }
1870 this._microtasks.push({
1871 func: task.invoke,
1872 args: additionalArgs,
1873 target: task.data && task.data.target
1874 });
1875 break;
1876 case 'macroTask':
1877 switch (task.source) {
1878 case 'setTimeout':
1879 task.data['handleId'] = this._setTimeout(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
1880 break;
1881 case 'setImmediate':
1882 task.data['handleId'] = this._setTimeout(task.invoke, 0, Array.prototype.slice.call(task.data['args'], 1));
1883 break;
1884 case 'setInterval':
1885 task.data['handleId'] = this._setInterval(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
1886 break;
1887 case 'XMLHttpRequest.send':
1888 throw new Error('Cannot make XHRs from within a fake async test. Request URL: ' +
1889 task.data['url']);
1890 case 'requestAnimationFrame':
1891 case 'webkitRequestAnimationFrame':
1892 case 'mozRequestAnimationFrame':
1893 // Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
1894 // (60 frames per second)
1895 task.data['handleId'] = this._setTimeout(task.invoke, 16, task.data['args'], this.trackPendingRequestAnimationFrame);
1896 break;
1897 default:
1898 // user can define which macroTask they want to support by passing
1899 // macroTaskOptions
1900 var macroTaskOption = this.findMacroTaskOption(task);
1901 if (macroTaskOption) {
1902 var args_1 = task.data && task.data['args'];
1903 var delay = args_1 && args_1.length > 1 ? args_1[1] : 0;
1904 var callbackArgs = macroTaskOption.callbackArgs ? macroTaskOption.callbackArgs : args_1;
1905 if (!!macroTaskOption.isPeriodic) {
1906 // periodic macroTask, use setInterval to simulate
1907 task.data['handleId'] = this._setInterval(task.invoke, delay, callbackArgs);
1908 task.data.isPeriodic = true;
1909 }
1910 else {
1911 // not periodic, use setTimeout to simulate
1912 task.data['handleId'] = this._setTimeout(task.invoke, delay, callbackArgs);
1913 }
1914 break;
1915 }
1916 throw new Error('Unknown macroTask scheduled in fake async test: ' + task.source);
1917 }
1918 break;
1919 case 'eventTask':
1920 task = delegate.scheduleTask(target, task);
1921 break;
1922 }
1923 return task;
1924 };
1925 FakeAsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
1926 switch (task.source) {
1927 case 'setTimeout':
1928 case 'requestAnimationFrame':
1929 case 'webkitRequestAnimationFrame':
1930 case 'mozRequestAnimationFrame':
1931 return this._clearTimeout(task.data['handleId']);
1932 case 'setInterval':
1933 return this._clearInterval(task.data['handleId']);
1934 default:
1935 // user can define which macroTask they want to support by passing
1936 // macroTaskOptions
1937 var macroTaskOption = this.findMacroTaskOption(task);
1938 if (macroTaskOption) {
1939 var handleId = task.data['handleId'];
1940 return macroTaskOption.isPeriodic ? this._clearInterval(handleId) :
1941 this._clearTimeout(handleId);
1942 }
1943 return delegate.cancelTask(target, task);
1944 }
1945 };
1946 FakeAsyncTestZoneSpec.prototype.onInvoke = function (delegate, current, target, callback, applyThis, applyArgs, source) {
1947 try {
1948 FakeAsyncTestZoneSpec.patchDate();
1949 return delegate.invoke(target, callback, applyThis, applyArgs, source);
1950 }
1951 finally {
1952 if (!this.patchDateLocked) {
1953 FakeAsyncTestZoneSpec.resetDate();
1954 }
1955 }
1956 };
1957 FakeAsyncTestZoneSpec.prototype.findMacroTaskOption = function (task) {
1958 if (!this.macroTaskOptions) {
1959 return null;
1960 }
1961 for (var i = 0; i < this.macroTaskOptions.length; i++) {
1962 var macroTaskOption = this.macroTaskOptions[i];
1963 if (macroTaskOption.source === task.source) {
1964 return macroTaskOption;
1965 }
1966 }
1967 return null;
1968 };
1969 FakeAsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
1970 this._lastError = error;
1971 return false; // Don't propagate error to parent zone.
1972 };
1973 return FakeAsyncTestZoneSpec;
1974 }());
1975 // Export the class so that new instances can be created with proper
1976 // constructor params.
1977 Zone['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
1978 })(typeof window === 'object' && window || typeof self === 'object' && self || global);
1979 Zone.__load_patch('fakeasync', function (global, Zone, api) {
1980 var FakeAsyncTestZoneSpec = Zone && Zone['FakeAsyncTestZoneSpec'];
1981 function getProxyZoneSpec() {
1982 return Zone && Zone['ProxyZoneSpec'];
1983 }
1984 var _fakeAsyncTestZoneSpec = null;
1985 /**
1986 * Clears out the shared fake async zone for a test.
1987 * To be called in a global `beforeEach`.
1988 *
1989 * @experimental
1990 */
1991 function resetFakeAsyncZone() {
1992 if (_fakeAsyncTestZoneSpec) {
1993 _fakeAsyncTestZoneSpec.unlockDatePatch();
1994 }
1995 _fakeAsyncTestZoneSpec = null;
1996 // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
1997 getProxyZoneSpec() && getProxyZoneSpec().assertPresent().resetDelegate();
1998 }
1999 /**
2000 * Wraps a function to be executed in the fakeAsync zone:
2001 * - microtasks are manually executed by calling `flushMicrotasks()`,
2002 * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
2003 *
2004 * If there are any pending timers at the end of the function, an exception will be thrown.
2005 *
2006 * Can be used to wrap inject() calls.
2007 *
2008 * ## Example
2009 *
2010 * {@example core/testing/ts/fake_async.ts region='basic'}
2011 *
2012 * @param fn
2013 * @returns The function wrapped to be executed in the fakeAsync zone
2014 *
2015 * @experimental
2016 */
2017 function fakeAsync(fn) {
2018 // Not using an arrow function to preserve context passed from call site
2019 var fakeAsyncFn = function () {
2020 var args = [];
2021 for (var _i = 0; _i < arguments.length; _i++) {
2022 args[_i] = arguments[_i];
2023 }
2024 var ProxyZoneSpec = getProxyZoneSpec();
2025 if (!ProxyZoneSpec) {
2026 throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
2027 'Please make sure that your environment includes zone.js/dist/proxy.js');
2028 }
2029 var proxyZoneSpec = ProxyZoneSpec.assertPresent();
2030 if (Zone.current.get('FakeAsyncTestZoneSpec')) {
2031 throw new Error('fakeAsync() calls can not be nested');
2032 }
2033 try {
2034 // in case jasmine.clock init a fakeAsyncTestZoneSpec
2035 if (!_fakeAsyncTestZoneSpec) {
2036 if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
2037 throw new Error('fakeAsync() calls can not be nested');
2038 }
2039 _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
2040 }
2041 var res = void 0;
2042 var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
2043 proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
2044 _fakeAsyncTestZoneSpec.lockDatePatch();
2045 try {
2046 res = fn.apply(this, args);
2047 flushMicrotasks();
2048 }
2049 finally {
2050 proxyZoneSpec.setDelegate(lastProxyZoneSpec);
2051 }
2052 if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
2053 throw new Error(_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length + " " +
2054 "periodic timer(s) still in the queue.");
2055 }
2056 if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
2057 throw new Error(_fakeAsyncTestZoneSpec.pendingTimers.length + " timer(s) still in the queue.");
2058 }
2059 return res;
2060 }
2061 finally {
2062 resetFakeAsyncZone();
2063 }
2064 };
2065 fakeAsyncFn.isFakeAsync = true;
2066 return fakeAsyncFn;
2067 }
2068 function _getFakeAsyncZoneSpec() {
2069 if (_fakeAsyncTestZoneSpec == null) {
2070 _fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
2071 if (_fakeAsyncTestZoneSpec == null) {
2072 throw new Error('The code should be running in the fakeAsync zone to call this function');
2073 }
2074 }
2075 return _fakeAsyncTestZoneSpec;
2076 }
2077 /**
2078 * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
2079 *
2080 * The microtasks queue is drained at the very start of this function and after any timer callback
2081 * has been executed.
2082 *
2083 * ## Example
2084 *
2085 * {@example core/testing/ts/fake_async.ts region='basic'}
2086 *
2087 * @experimental
2088 */
2089 function tick(millis, ignoreNestedTimeout) {
2090 if (millis === void 0) { millis = 0; }
2091 if (ignoreNestedTimeout === void 0) { ignoreNestedTimeout = false; }
2092 _getFakeAsyncZoneSpec().tick(millis, null, ignoreNestedTimeout);
2093 }
2094 /**
2095 * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
2096 * draining the macrotask queue until it is empty. The returned value is the milliseconds
2097 * of time that would have been elapsed.
2098 *
2099 * @param maxTurns
2100 * @returns The simulated time elapsed, in millis.
2101 *
2102 * @experimental
2103 */
2104 function flush(maxTurns) {
2105 return _getFakeAsyncZoneSpec().flush(maxTurns);
2106 }
2107 /**
2108 * Discard all remaining periodic tasks.
2109 *
2110 * @experimental
2111 */
2112 function discardPeriodicTasks() {
2113 var zoneSpec = _getFakeAsyncZoneSpec();
2114 var pendingTimers = zoneSpec.pendingPeriodicTimers;
2115 zoneSpec.pendingPeriodicTimers.length = 0;
2116 }
2117 /**
2118 * Flush any pending microtasks.
2119 *
2120 * @experimental
2121 */
2122 function flushMicrotasks() {
2123 _getFakeAsyncZoneSpec().flushMicrotasks();
2124 }
2125 Zone[api.symbol('fakeAsyncTest')] =
2126 { resetFakeAsyncZone: resetFakeAsyncZone, flushMicrotasks: flushMicrotasks, discardPeriodicTasks: discardPeriodicTasks, tick: tick, flush: flush, fakeAsync: fakeAsync };
2127 }, true);
2128 /**
2129 * @license
2130 * Copyright Google LLC All Rights Reserved.
2131 *
2132 * Use of this source code is governed by an MIT-style license that can be
2133 * found in the LICENSE file at https://angular.io/license
2134 */
2135 /**
2136 * Promise for async/fakeAsync zoneSpec test
2137 * can support async operation which not supported by zone.js
2138 * such as
2139 * it ('test jsonp in AsyncZone', async() => {
2140 * new Promise(res => {
2141 * jsonp(url, (data) => {
2142 * // success callback
2143 * res(data);
2144 * });
2145 * }).then((jsonpResult) => {
2146 * // get jsonp result.
2147 *
2148 * // user will expect AsyncZoneSpec wait for
2149 * // then, but because jsonp is not zone aware
2150 * // AsyncZone will finish before then is called.
2151 * });
2152 * });
2153 */
2154 Zone.__load_patch('promisefortest', function (global, Zone, api) {
2155 var symbolState = api.symbol('state');
2156 var UNRESOLVED = null;
2157 var symbolParentUnresolved = api.symbol('parentUnresolved');
2158 // patch Promise.prototype.then to keep an internal
2159 // number for tracking unresolved chained promise
2160 // we will decrease this number when the parent promise
2161 // being resolved/rejected and chained promise was
2162 // scheduled as a microTask.
2163 // so we can know such kind of chained promise still
2164 // not resolved in AsyncTestZone
2165 Promise[api.symbol('patchPromiseForTest')] = function patchPromiseForTest() {
2166 var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
2167 if (oriThen) {
2168 return;
2169 }
2170 oriThen = Promise[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
2171 Promise.prototype.then = function () {
2172 var chained = oriThen.apply(this, arguments);
2173 if (this[symbolState] === UNRESOLVED) {
2174 // parent promise is unresolved.
2175 var asyncTestZoneSpec = Zone.current.get('AsyncTestZoneSpec');
2176 if (asyncTestZoneSpec) {
2177 asyncTestZoneSpec.unresolvedChainedPromiseCount++;
2178 chained[symbolParentUnresolved] = true;
2179 }
2180 }
2181 return chained;
2182 };
2183 };
2184 Promise[api.symbol('unPatchPromiseForTest')] = function unpatchPromiseForTest() {
2185 // restore origin then
2186 var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
2187 if (oriThen) {
2188 Promise.prototype.then = oriThen;
2189 Promise[Zone.__symbol__('ZonePromiseThen')] = undefined;
2190 }
2191 };
2192 });
2193})));
Note: See TracBrowser for help on using the repository browser.