zone-testing.js 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (factory());
  12. }(this, (function () { 'use strict';
  13. /**
  14. * @license
  15. * Copyright Google Inc. All Rights Reserved.
  16. *
  17. * Use of this source code is governed by an MIT-style license that can be
  18. * found in the LICENSE file at https://angular.io/license
  19. */
  20. /**
  21. * @fileoverview
  22. * @suppress {globalThis}
  23. */
  24. var __assign = (undefined && undefined.__assign) || function () {
  25. __assign = Object.assign || function(t) {
  26. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27. s = arguments[i];
  28. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29. t[p] = s[p];
  30. }
  31. return t;
  32. };
  33. return __assign.apply(this, arguments);
  34. };
  35. var NEWLINE = '\n';
  36. var IGNORE_FRAMES = {};
  37. var creationTrace = '__creationTrace__';
  38. var ERROR_TAG = 'STACKTRACE TRACKING';
  39. var SEP_TAG = '__SEP_TAG__';
  40. var sepTemplate = SEP_TAG + '@[native]';
  41. var LongStackTrace = /** @class */ (function () {
  42. function LongStackTrace() {
  43. this.error = getStacktrace();
  44. this.timestamp = new Date();
  45. }
  46. return LongStackTrace;
  47. }());
  48. function getStacktraceWithUncaughtError() {
  49. return new Error(ERROR_TAG);
  50. }
  51. function getStacktraceWithCaughtError() {
  52. try {
  53. throw getStacktraceWithUncaughtError();
  54. }
  55. catch (err) {
  56. return err;
  57. }
  58. }
  59. // Some implementations of exception handling don't create a stack trace if the exception
  60. // isn't thrown, however it's faster not to actually throw the exception.
  61. var error = getStacktraceWithUncaughtError();
  62. var caughtError = getStacktraceWithCaughtError();
  63. var getStacktrace = error.stack ?
  64. getStacktraceWithUncaughtError :
  65. (caughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
  66. function getFrames(error) {
  67. return error.stack ? error.stack.split(NEWLINE) : [];
  68. }
  69. function addErrorStack(lines, error) {
  70. var trace = getFrames(error);
  71. for (var i = 0; i < trace.length; i++) {
  72. var frame = trace[i];
  73. // Filter out the Frames which are part of stack capturing.
  74. if (!IGNORE_FRAMES.hasOwnProperty(frame)) {
  75. lines.push(trace[i]);
  76. }
  77. }
  78. }
  79. function renderLongStackTrace(frames, stack) {
  80. var longTrace = [stack ? stack.trim() : ''];
  81. if (frames) {
  82. var timestamp = new Date().getTime();
  83. for (var i = 0; i < frames.length; i++) {
  84. var traceFrames = frames[i];
  85. var lastTime = traceFrames.timestamp;
  86. var separator = "____________________Elapsed " + (timestamp - lastTime.getTime()) + " ms; At: " + lastTime;
  87. separator = separator.replace(/[^\w\d]/g, '_');
  88. longTrace.push(sepTemplate.replace(SEP_TAG, separator));
  89. addErrorStack(longTrace, traceFrames.error);
  90. timestamp = lastTime.getTime();
  91. }
  92. }
  93. return longTrace.join(NEWLINE);
  94. }
  95. Zone['longStackTraceZoneSpec'] = {
  96. name: 'long-stack-trace',
  97. longStackTraceLimit: 10,
  98. // add a getLongStackTrace method in spec to
  99. // handle handled reject promise error.
  100. getLongStackTrace: function (error) {
  101. if (!error) {
  102. return undefined;
  103. }
  104. var trace = error[Zone.__symbol__('currentTaskTrace')];
  105. if (!trace) {
  106. return error.stack;
  107. }
  108. return renderLongStackTrace(trace, error.stack);
  109. },
  110. onScheduleTask: function (parentZoneDelegate, currentZone, targetZone, task) {
  111. if (Error.stackTraceLimit > 0) {
  112. // if Error.stackTraceLimit is 0, means stack trace
  113. // is disabled, so we don't need to generate long stack trace
  114. // this will improve performance in some test(some test will
  115. // set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
  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 = __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 (Error.stackTraceLimit > 0) {
  138. // if Error.stackTraceLimit is 0, means stack trace
  139. // is disabled, so we don't need to generate long stack trace
  140. // this will improve performance in some test(some test will
  141. // set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
  142. var parentTask = Zone.currentTask || error.task;
  143. if (error instanceof Error && parentTask) {
  144. var longStack = renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
  145. try {
  146. error.stack = error.longStack = longStack;
  147. }
  148. catch (err) {
  149. }
  150. }
  151. }
  152. return parentZoneDelegate.handleError(targetZone, error);
  153. }
  154. };
  155. function captureStackTraces(stackTraces, count) {
  156. if (count > 0) {
  157. stackTraces.push(getFrames((new LongStackTrace()).error));
  158. captureStackTraces(stackTraces, count - 1);
  159. }
  160. }
  161. function computeIgnoreFrames() {
  162. if (Error.stackTraceLimit <= 0) {
  163. return;
  164. }
  165. var frames = [];
  166. captureStackTraces(frames, 2);
  167. var frames1 = frames[0];
  168. var frames2 = frames[1];
  169. for (var i = 0; i < frames1.length; i++) {
  170. var frame1 = frames1[i];
  171. if (frame1.indexOf(ERROR_TAG) == -1) {
  172. var match = frame1.match(/^\s*at\s+/);
  173. if (match) {
  174. sepTemplate = match[0] + SEP_TAG + ' (http://localhost)';
  175. break;
  176. }
  177. }
  178. }
  179. for (var i = 0; i < frames1.length; i++) {
  180. var frame1 = frames1[i];
  181. var frame2 = frames2[i];
  182. if (frame1 === frame2) {
  183. IGNORE_FRAMES[frame1] = true;
  184. }
  185. else {
  186. break;
  187. }
  188. }
  189. }
  190. computeIgnoreFrames();
  191. /**
  192. * @license
  193. * Copyright Google Inc. All Rights Reserved.
  194. *
  195. * Use of this source code is governed by an MIT-style license that can be
  196. * found in the LICENSE file at https://angular.io/license
  197. */
  198. var ProxyZoneSpec = /** @class */ (function () {
  199. function ProxyZoneSpec(defaultSpecDelegate) {
  200. if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
  201. this.defaultSpecDelegate = defaultSpecDelegate;
  202. this.name = 'ProxyZone';
  203. this._delegateSpec = null;
  204. this.properties = { 'ProxyZoneSpec': this };
  205. this.propertyKeys = null;
  206. this.lastTaskState = null;
  207. this.isNeedToTriggerHasTask = false;
  208. this.tasks = [];
  209. this.setDelegate(defaultSpecDelegate);
  210. }
  211. ProxyZoneSpec.get = function () {
  212. return Zone.current.get('ProxyZoneSpec');
  213. };
  214. ProxyZoneSpec.isLoaded = function () {
  215. return ProxyZoneSpec.get() instanceof ProxyZoneSpec;
  216. };
  217. ProxyZoneSpec.assertPresent = function () {
  218. if (!ProxyZoneSpec.isLoaded()) {
  219. throw new Error("Expected to be running in 'ProxyZone', but it was not found.");
  220. }
  221. return ProxyZoneSpec.get();
  222. };
  223. ProxyZoneSpec.prototype.setDelegate = function (delegateSpec) {
  224. var _this = this;
  225. var isNewDelegate = this._delegateSpec !== delegateSpec;
  226. this._delegateSpec = delegateSpec;
  227. this.propertyKeys && this.propertyKeys.forEach(function (key) { return delete _this.properties[key]; });
  228. this.propertyKeys = null;
  229. if (delegateSpec && delegateSpec.properties) {
  230. this.propertyKeys = Object.keys(delegateSpec.properties);
  231. this.propertyKeys.forEach(function (k) { return _this.properties[k] = delegateSpec.properties[k]; });
  232. }
  233. // if set a new delegateSpec, shoulde check whether need to
  234. // trigger hasTask or not
  235. if (isNewDelegate && this.lastTaskState &&
  236. (this.lastTaskState.macroTask || this.lastTaskState.microTask)) {
  237. this.isNeedToTriggerHasTask = true;
  238. }
  239. };
  240. ProxyZoneSpec.prototype.getDelegate = function () {
  241. return this._delegateSpec;
  242. };
  243. ProxyZoneSpec.prototype.resetDelegate = function () {
  244. var delegateSpec = this.getDelegate();
  245. this.setDelegate(this.defaultSpecDelegate);
  246. };
  247. ProxyZoneSpec.prototype.tryTriggerHasTask = function (parentZoneDelegate, currentZone, targetZone) {
  248. if (this.isNeedToTriggerHasTask && this.lastTaskState) {
  249. // last delegateSpec has microTask or macroTask
  250. // should call onHasTask in current delegateSpec
  251. this.isNeedToTriggerHasTask = false;
  252. this.onHasTask(parentZoneDelegate, currentZone, targetZone, this.lastTaskState);
  253. }
  254. };
  255. ProxyZoneSpec.prototype.removeFromTasks = function (task) {
  256. if (!this.tasks) {
  257. return;
  258. }
  259. for (var i = 0; i < this.tasks.length; i++) {
  260. if (this.tasks[i] === task) {
  261. this.tasks.splice(i, 1);
  262. return;
  263. }
  264. }
  265. };
  266. ProxyZoneSpec.prototype.getAndClearPendingTasksInfo = function () {
  267. if (this.tasks.length === 0) {
  268. return '';
  269. }
  270. var taskInfo = this.tasks.map(function (task) {
  271. var dataInfo = task.data &&
  272. Object.keys(task.data)
  273. .map(function (key) {
  274. return key + ':' + task.data[key];
  275. })
  276. .join(',');
  277. return "type: " + task.type + ", source: " + task.source + ", args: {" + dataInfo + "}";
  278. });
  279. var pendingTasksInfo = '--Pendng async tasks are: [' + taskInfo + ']';
  280. // clear tasks
  281. this.tasks = [];
  282. return pendingTasksInfo;
  283. };
  284. ProxyZoneSpec.prototype.onFork = function (parentZoneDelegate, currentZone, targetZone, zoneSpec) {
  285. if (this._delegateSpec && this._delegateSpec.onFork) {
  286. return this._delegateSpec.onFork(parentZoneDelegate, currentZone, targetZone, zoneSpec);
  287. }
  288. else {
  289. return parentZoneDelegate.fork(targetZone, zoneSpec);
  290. }
  291. };
  292. ProxyZoneSpec.prototype.onIntercept = function (parentZoneDelegate, currentZone, targetZone, delegate, source) {
  293. if (this._delegateSpec && this._delegateSpec.onIntercept) {
  294. return this._delegateSpec.onIntercept(parentZoneDelegate, currentZone, targetZone, delegate, source);
  295. }
  296. else {
  297. return parentZoneDelegate.intercept(targetZone, delegate, source);
  298. }
  299. };
  300. ProxyZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  301. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  302. if (this._delegateSpec && this._delegateSpec.onInvoke) {
  303. return this._delegateSpec.onInvoke(parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source);
  304. }
  305. else {
  306. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  307. }
  308. };
  309. ProxyZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  310. if (this._delegateSpec && this._delegateSpec.onHandleError) {
  311. return this._delegateSpec.onHandleError(parentZoneDelegate, currentZone, targetZone, error);
  312. }
  313. else {
  314. return parentZoneDelegate.handleError(targetZone, error);
  315. }
  316. };
  317. ProxyZoneSpec.prototype.onScheduleTask = function (parentZoneDelegate, currentZone, targetZone, task) {
  318. if (task.type !== 'eventTask') {
  319. this.tasks.push(task);
  320. }
  321. if (this._delegateSpec && this._delegateSpec.onScheduleTask) {
  322. return this._delegateSpec.onScheduleTask(parentZoneDelegate, currentZone, targetZone, task);
  323. }
  324. else {
  325. return parentZoneDelegate.scheduleTask(targetZone, task);
  326. }
  327. };
  328. ProxyZoneSpec.prototype.onInvokeTask = function (parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs) {
  329. if (task.type !== 'eventTask') {
  330. this.removeFromTasks(task);
  331. }
  332. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  333. if (this._delegateSpec && this._delegateSpec.onInvokeTask) {
  334. return this._delegateSpec.onInvokeTask(parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs);
  335. }
  336. else {
  337. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  338. }
  339. };
  340. ProxyZoneSpec.prototype.onCancelTask = function (parentZoneDelegate, currentZone, targetZone, task) {
  341. if (task.type !== 'eventTask') {
  342. this.removeFromTasks(task);
  343. }
  344. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  345. if (this._delegateSpec && this._delegateSpec.onCancelTask) {
  346. return this._delegateSpec.onCancelTask(parentZoneDelegate, currentZone, targetZone, task);
  347. }
  348. else {
  349. return parentZoneDelegate.cancelTask(targetZone, task);
  350. }
  351. };
  352. ProxyZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  353. this.lastTaskState = hasTaskState;
  354. if (this._delegateSpec && this._delegateSpec.onHasTask) {
  355. this._delegateSpec.onHasTask(delegate, current, target, hasTaskState);
  356. }
  357. else {
  358. delegate.hasTask(target, hasTaskState);
  359. }
  360. };
  361. return ProxyZoneSpec;
  362. }());
  363. // Export the class so that new instances can be created with proper
  364. // constructor params.
  365. Zone['ProxyZoneSpec'] = ProxyZoneSpec;
  366. /**
  367. * @license
  368. * Copyright Google Inc. All Rights Reserved.
  369. *
  370. * Use of this source code is governed by an MIT-style license that can be
  371. * found in the LICENSE file at https://angular.io/license
  372. */
  373. var SyncTestZoneSpec = /** @class */ (function () {
  374. function SyncTestZoneSpec(namePrefix) {
  375. this.runZone = Zone.current;
  376. this.name = 'syncTestZone for ' + namePrefix;
  377. }
  378. SyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  379. switch (task.type) {
  380. case 'microTask':
  381. case 'macroTask':
  382. throw new Error("Cannot call " + task.source + " from within a sync test.");
  383. case 'eventTask':
  384. task = delegate.scheduleTask(target, task);
  385. break;
  386. }
  387. return task;
  388. };
  389. return SyncTestZoneSpec;
  390. }());
  391. // Export the class so that new instances can be created with proper
  392. // constructor params.
  393. Zone['SyncTestZoneSpec'] = SyncTestZoneSpec;
  394. /**
  395. * @license
  396. * Copyright Google Inc. All Rights Reserved.
  397. *
  398. * Use of this source code is governed by an MIT-style license that can be
  399. * found in the LICENSE file at https://angular.io/license
  400. */
  401. (function () {
  402. var __extends = function (d, b) {
  403. for (var p in b)
  404. if (b.hasOwnProperty(p))
  405. d[p] = b[p];
  406. function __() {
  407. this.constructor = d;
  408. }
  409. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  410. };
  411. var _global = typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global;
  412. // Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
  413. // in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
  414. if (!Zone)
  415. throw new Error('Missing: zone.js');
  416. if (typeof jasmine == 'undefined')
  417. throw new Error('Missing: jasmine.js');
  418. if (jasmine['__zone_patch__'])
  419. throw new Error("'jasmine' has already been patched with 'Zone'.");
  420. jasmine['__zone_patch__'] = true;
  421. var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  422. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  423. if (!SyncTestZoneSpec)
  424. throw new Error('Missing: SyncTestZoneSpec');
  425. if (!ProxyZoneSpec)
  426. throw new Error('Missing: ProxyZoneSpec');
  427. var ambientZone = Zone.current;
  428. // Create a synchronous-only zone in which to run `describe` blocks in order to raise an
  429. // error if any asynchronous operations are attempted inside of a `describe` but outside of
  430. // a `beforeEach` or `it`.
  431. var syncZone = ambientZone.fork(new SyncTestZoneSpec('jasmine.describe'));
  432. var symbol = Zone.__symbol__;
  433. // whether patch jasmine clock when in fakeAsync
  434. var disablePatchingJasmineClock = _global[symbol('fakeAsyncDisablePatchingClock')] === true;
  435. // the original variable name fakeAsyncPatchLock is not accurate, so the name will be
  436. // fakeAsyncAutoFakeAsyncWhenClockPatched and if this enablePatchingJasmineClock is false, we also
  437. // automatically disable the auto jump into fakeAsync feature
  438. var enableAutoFakeAsyncWhenClockPatched = !disablePatchingJasmineClock &&
  439. ((_global[symbol('fakeAsyncPatchLock')] === true) ||
  440. (_global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true));
  441. var ignoreUnhandledRejection = _global[symbol('ignoreUnhandledRejection')] === true;
  442. if (!ignoreUnhandledRejection) {
  443. var globalErrors_1 = jasmine.GlobalErrors;
  444. if (globalErrors_1 && !jasmine[symbol('GlobalErrors')]) {
  445. jasmine[symbol('GlobalErrors')] = globalErrors_1;
  446. jasmine.GlobalErrors = function () {
  447. var instance = new globalErrors_1();
  448. var originalInstall = instance.install;
  449. if (originalInstall && !instance[symbol('install')]) {
  450. instance[symbol('install')] = originalInstall;
  451. instance.install = function () {
  452. var originalHandlers = process.listeners('unhandledRejection');
  453. var r = originalInstall.apply(this, arguments);
  454. process.removeAllListeners('unhandledRejection');
  455. if (originalHandlers) {
  456. originalHandlers.forEach(function (h) { return process.on('unhandledRejection', h); });
  457. }
  458. return r;
  459. };
  460. }
  461. return instance;
  462. };
  463. }
  464. }
  465. // Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
  466. var jasmineEnv = jasmine.getEnv();
  467. ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
  468. var originalJasmineFn = jasmineEnv[methodName];
  469. jasmineEnv[methodName] = function (description, specDefinitions) {
  470. return originalJasmineFn.call(this, description, wrapDescribeInZone(specDefinitions));
  471. };
  472. });
  473. ['it', 'xit', 'fit'].forEach(function (methodName) {
  474. var originalJasmineFn = jasmineEnv[methodName];
  475. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  476. jasmineEnv[methodName] = function (description, specDefinitions, timeout) {
  477. arguments[1] = wrapTestInZone(specDefinitions);
  478. return originalJasmineFn.apply(this, arguments);
  479. };
  480. });
  481. ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(function (methodName) {
  482. var originalJasmineFn = jasmineEnv[methodName];
  483. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  484. jasmineEnv[methodName] = function (specDefinitions, timeout) {
  485. arguments[0] = wrapTestInZone(specDefinitions);
  486. return originalJasmineFn.apply(this, arguments);
  487. };
  488. });
  489. if (!disablePatchingJasmineClock) {
  490. // need to patch jasmine.clock().mockDate and jasmine.clock().tick() so
  491. // they can work properly in FakeAsyncTest
  492. var originalClockFn_1 = (jasmine[symbol('clock')] = jasmine['clock']);
  493. jasmine['clock'] = function () {
  494. var clock = originalClockFn_1.apply(this, arguments);
  495. if (!clock[symbol('patched')]) {
  496. clock[symbol('patched')] = symbol('patched');
  497. var originalTick_1 = (clock[symbol('tick')] = clock.tick);
  498. clock.tick = function () {
  499. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  500. if (fakeAsyncZoneSpec) {
  501. return fakeAsyncZoneSpec.tick.apply(fakeAsyncZoneSpec, arguments);
  502. }
  503. return originalTick_1.apply(this, arguments);
  504. };
  505. var originalMockDate_1 = (clock[symbol('mockDate')] = clock.mockDate);
  506. clock.mockDate = function () {
  507. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  508. if (fakeAsyncZoneSpec) {
  509. var dateTime = arguments.length > 0 ? arguments[0] : new Date();
  510. return fakeAsyncZoneSpec.setCurrentRealTime.apply(fakeAsyncZoneSpec, dateTime && typeof dateTime.getTime === 'function' ? [dateTime.getTime()] :
  511. arguments);
  512. }
  513. return originalMockDate_1.apply(this, arguments);
  514. };
  515. // for auto go into fakeAsync feature, we need the flag to enable it
  516. if (enableAutoFakeAsyncWhenClockPatched) {
  517. ['install', 'uninstall'].forEach(function (methodName) {
  518. var originalClockFn = (clock[symbol(methodName)] = clock[methodName]);
  519. clock[methodName] = function () {
  520. var FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec'];
  521. if (FakeAsyncTestZoneSpec) {
  522. jasmine[symbol('clockInstalled')] = 'install' === methodName;
  523. return;
  524. }
  525. return originalClockFn.apply(this, arguments);
  526. };
  527. });
  528. }
  529. }
  530. return clock;
  531. };
  532. }
  533. /**
  534. * Gets a function wrapping the body of a Jasmine `describe` block to execute in a
  535. * synchronous-only zone.
  536. */
  537. function wrapDescribeInZone(describeBody) {
  538. return function () {
  539. return syncZone.run(describeBody, this, arguments);
  540. };
  541. }
  542. function runInTestZone(testBody, applyThis, queueRunner, done) {
  543. var isClockInstalled = !!jasmine[symbol('clockInstalled')];
  544. var testProxyZoneSpec = queueRunner.testProxyZoneSpec;
  545. var testProxyZone = queueRunner.testProxyZone;
  546. if (isClockInstalled && enableAutoFakeAsyncWhenClockPatched) {
  547. // auto run a fakeAsync
  548. var fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
  549. if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
  550. testBody = fakeAsyncModule.fakeAsync(testBody);
  551. }
  552. }
  553. if (done) {
  554. return testProxyZone.run(testBody, applyThis, [done]);
  555. }
  556. else {
  557. return testProxyZone.run(testBody, applyThis);
  558. }
  559. }
  560. /**
  561. * Gets a function wrapping the body of a Jasmine `it/beforeEach/afterEach` block to
  562. * execute in a ProxyZone zone.
  563. * This will run in `testProxyZone`. The `testProxyZone` will be reset by the `ZoneQueueRunner`
  564. */
  565. function wrapTestInZone(testBody) {
  566. // The `done` callback is only passed through if the function expects at least one argument.
  567. // Note we have to make a function with correct number of arguments, otherwise jasmine will
  568. // think that all functions are sync or async.
  569. return (testBody && (testBody.length ? function (done) {
  570. return runInTestZone(testBody, this, this.queueRunner, done);
  571. } : function () {
  572. return runInTestZone(testBody, this, this.queueRunner);
  573. }));
  574. }
  575. var QueueRunner = jasmine.QueueRunner;
  576. jasmine.QueueRunner = (function (_super) {
  577. __extends(ZoneQueueRunner, _super);
  578. function ZoneQueueRunner(attrs) {
  579. var _this = this;
  580. attrs.onComplete = (function (fn) { return function () {
  581. // All functions are done, clear the test zone.
  582. _this.testProxyZone = null;
  583. _this.testProxyZoneSpec = null;
  584. ambientZone.scheduleMicroTask('jasmine.onComplete', fn);
  585. }; })(attrs.onComplete);
  586. var nativeSetTimeout = _global['__zone_symbol__setTimeout'];
  587. var nativeClearTimeout = _global['__zone_symbol__clearTimeout'];
  588. if (nativeSetTimeout) {
  589. // should run setTimeout inside jasmine outside of zone
  590. attrs.timeout = {
  591. setTimeout: nativeSetTimeout ? nativeSetTimeout : _global.setTimeout,
  592. clearTimeout: nativeClearTimeout ? nativeClearTimeout : _global.clearTimeout
  593. };
  594. }
  595. // create a userContext to hold the queueRunner itself
  596. // so we can access the testProxy in it/xit/beforeEach ...
  597. if (jasmine.UserContext) {
  598. if (!attrs.userContext) {
  599. attrs.userContext = new jasmine.UserContext();
  600. }
  601. attrs.userContext.queueRunner = this;
  602. }
  603. else {
  604. if (!attrs.userContext) {
  605. attrs.userContext = {};
  606. }
  607. attrs.userContext.queueRunner = this;
  608. }
  609. // patch attrs.onException
  610. var onException = attrs.onException;
  611. attrs.onException = function (error) {
  612. if (error &&
  613. error.message ===
  614. 'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.') {
  615. // jasmine timeout, we can make the error message more
  616. // reasonable to tell what tasks are pending
  617. var proxyZoneSpec = this && this.testProxyZoneSpec;
  618. if (proxyZoneSpec) {
  619. var pendingTasksInfo = proxyZoneSpec.getAndClearPendingTasksInfo();
  620. try {
  621. // try catch here in case error.message is not writable
  622. error.message += pendingTasksInfo;
  623. }
  624. catch (err) {
  625. }
  626. }
  627. }
  628. if (onException) {
  629. onException.call(this, error);
  630. }
  631. };
  632. _super.call(this, attrs);
  633. }
  634. ZoneQueueRunner.prototype.execute = function () {
  635. var _this = this;
  636. var zone = Zone.current;
  637. var isChildOfAmbientZone = false;
  638. while (zone) {
  639. if (zone === ambientZone) {
  640. isChildOfAmbientZone = true;
  641. break;
  642. }
  643. zone = zone.parent;
  644. }
  645. if (!isChildOfAmbientZone)
  646. throw new Error('Unexpected Zone: ' + Zone.current.name);
  647. // This is the zone which will be used for running individual tests.
  648. // It will be a proxy zone, so that the tests function can retroactively install
  649. // different zones.
  650. // Example:
  651. // - In beforeEach() do childZone = Zone.current.fork(...);
  652. // - In it() try to do fakeAsync(). The issue is that because the beforeEach forked the
  653. // zone outside of fakeAsync it will be able to escape the fakeAsync rules.
  654. // - Because ProxyZone is parent fo `childZone` fakeAsync can retroactively add
  655. // fakeAsync behavior to the childZone.
  656. this.testProxyZoneSpec = new ProxyZoneSpec();
  657. this.testProxyZone = ambientZone.fork(this.testProxyZoneSpec);
  658. if (!Zone.currentTask) {
  659. // if we are not running in a task then if someone would register a
  660. // element.addEventListener and then calling element.click() the
  661. // addEventListener callback would think that it is the top most task and would
  662. // drain the microtask queue on element.click() which would be incorrect.
  663. // For this reason we always force a task when running jasmine tests.
  664. Zone.current.scheduleMicroTask('jasmine.execute().forceTask', function () { return QueueRunner.prototype.execute.call(_this); });
  665. }
  666. else {
  667. _super.prototype.execute.call(this);
  668. }
  669. };
  670. return ZoneQueueRunner;
  671. })(QueueRunner);
  672. })();
  673. /**
  674. * @license
  675. * Copyright Google Inc. All Rights Reserved.
  676. *
  677. * Use of this source code is governed by an MIT-style license that can be
  678. * found in the LICENSE file at https://angular.io/license
  679. */
  680. var _global = typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global;
  681. var AsyncTestZoneSpec = /** @class */ (function () {
  682. function AsyncTestZoneSpec(finishCallback, failCallback, namePrefix) {
  683. this.finishCallback = finishCallback;
  684. this.failCallback = failCallback;
  685. this._pendingMicroTasks = false;
  686. this._pendingMacroTasks = false;
  687. this._alreadyErrored = false;
  688. this._isSync = false;
  689. this.runZone = Zone.current;
  690. this.unresolvedChainedPromiseCount = 0;
  691. this.supportWaitUnresolvedChainedPromise = false;
  692. this.name = 'asyncTestZone for ' + namePrefix;
  693. this.properties = { 'AsyncTestZoneSpec': this };
  694. this.supportWaitUnresolvedChainedPromise =
  695. _global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] === true;
  696. }
  697. AsyncTestZoneSpec.prototype.isUnresolvedChainedPromisePending = function () {
  698. return this.unresolvedChainedPromiseCount > 0;
  699. };
  700. AsyncTestZoneSpec.prototype._finishCallbackIfDone = function () {
  701. var _this = this;
  702. if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
  703. (this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending()))) {
  704. // We do this because we would like to catch unhandled rejected promises.
  705. this.runZone.run(function () {
  706. setTimeout(function () {
  707. if (!_this._alreadyErrored && !(_this._pendingMicroTasks || _this._pendingMacroTasks)) {
  708. _this.finishCallback();
  709. }
  710. }, 0);
  711. });
  712. }
  713. };
  714. AsyncTestZoneSpec.prototype.patchPromiseForTest = function () {
  715. if (!this.supportWaitUnresolvedChainedPromise) {
  716. return;
  717. }
  718. var patchPromiseForTest = Promise[Zone.__symbol__('patchPromiseForTest')];
  719. if (patchPromiseForTest) {
  720. patchPromiseForTest();
  721. }
  722. };
  723. AsyncTestZoneSpec.prototype.unPatchPromiseForTest = function () {
  724. if (!this.supportWaitUnresolvedChainedPromise) {
  725. return;
  726. }
  727. var unPatchPromiseForTest = Promise[Zone.__symbol__('unPatchPromiseForTest')];
  728. if (unPatchPromiseForTest) {
  729. unPatchPromiseForTest();
  730. }
  731. };
  732. AsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  733. if (task.type !== 'eventTask') {
  734. this._isSync = false;
  735. }
  736. if (task.type === 'microTask' && task.data && task.data instanceof Promise) {
  737. // check whether the promise is a chained promise
  738. if (task.data[AsyncTestZoneSpec.symbolParentUnresolved] === true) {
  739. // chained promise is being scheduled
  740. this.unresolvedChainedPromiseCount--;
  741. }
  742. }
  743. return delegate.scheduleTask(target, task);
  744. };
  745. AsyncTestZoneSpec.prototype.onInvokeTask = function (delegate, current, target, task, applyThis, applyArgs) {
  746. if (task.type !== 'eventTask') {
  747. this._isSync = false;
  748. }
  749. return delegate.invokeTask(target, task, applyThis, applyArgs);
  750. };
  751. AsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  752. if (task.type !== 'eventTask') {
  753. this._isSync = false;
  754. }
  755. return delegate.cancelTask(target, task);
  756. };
  757. // Note - we need to use onInvoke at the moment to call finish when a test is
  758. // fully synchronous. TODO(juliemr): remove this when the logic for
  759. // onHasTask changes and it calls whenever the task queues are dirty.
  760. // updated by(JiaLiPassion), only call finish callback when no task
  761. // was scheduled/invoked/canceled.
  762. AsyncTestZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  763. try {
  764. this._isSync = true;
  765. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  766. }
  767. finally {
  768. var afterTaskCounts = parentZoneDelegate._taskCounts;
  769. if (this._isSync) {
  770. this._finishCallbackIfDone();
  771. }
  772. }
  773. };
  774. AsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  775. // Let the parent try to handle the error.
  776. var result = parentZoneDelegate.handleError(targetZone, error);
  777. if (result) {
  778. this.failCallback(error);
  779. this._alreadyErrored = true;
  780. }
  781. return false;
  782. };
  783. AsyncTestZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  784. delegate.hasTask(target, hasTaskState);
  785. if (hasTaskState.change == 'microTask') {
  786. this._pendingMicroTasks = hasTaskState.microTask;
  787. this._finishCallbackIfDone();
  788. }
  789. else if (hasTaskState.change == 'macroTask') {
  790. this._pendingMacroTasks = hasTaskState.macroTask;
  791. this._finishCallbackIfDone();
  792. }
  793. };
  794. AsyncTestZoneSpec.symbolParentUnresolved = Zone.__symbol__('parentUnresolved');
  795. return AsyncTestZoneSpec;
  796. }());
  797. // Export the class so that new instances can be created with proper
  798. // constructor params.
  799. Zone['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
  800. /**
  801. * @license
  802. * Copyright Google Inc. All Rights Reserved.
  803. *
  804. * Use of this source code is governed by an MIT-style license that can be
  805. * found in the LICENSE file at https://angular.io/license
  806. */
  807. Zone.__load_patch('asynctest', function (global, Zone, api) {
  808. /**
  809. * Wraps a test function in an asynchronous test zone. The test will automatically
  810. * complete when all asynchronous calls within this zone are done.
  811. */
  812. Zone[api.symbol('asyncTest')] = function asyncTest(fn) {
  813. // If we're running using the Jasmine test framework, adapt to call the 'done'
  814. // function when asynchronous activity is finished.
  815. if (global.jasmine) {
  816. // Not using an arrow function to preserve context passed from call site
  817. return function (done) {
  818. if (!done) {
  819. // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
  820. // fake it here and assume sync.
  821. done = function () { };
  822. done.fail = function (e) {
  823. throw e;
  824. };
  825. }
  826. runInTestZone(fn, this, done, function (err) {
  827. if (typeof err === 'string') {
  828. return done.fail(new Error(err));
  829. }
  830. else {
  831. done.fail(err);
  832. }
  833. });
  834. };
  835. }
  836. // Otherwise, return a promise which will resolve when asynchronous activity
  837. // is finished. This will be correctly consumed by the Mocha framework with
  838. // it('...', async(myFn)); or can be used in a custom framework.
  839. // Not using an arrow function to preserve context passed from call site
  840. return function () {
  841. var _this = this;
  842. return new Promise(function (finishCallback, failCallback) {
  843. runInTestZone(fn, _this, finishCallback, failCallback);
  844. });
  845. };
  846. };
  847. function runInTestZone(fn, context, finishCallback, failCallback) {
  848. var currentZone = Zone.current;
  849. var AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
  850. if (AsyncTestZoneSpec === undefined) {
  851. throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
  852. 'Please make sure that your environment includes zone.js/dist/async-test.js');
  853. }
  854. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  855. if (ProxyZoneSpec === undefined) {
  856. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  857. 'Please make sure that your environment includes zone.js/dist/proxy.js');
  858. }
  859. var proxyZoneSpec = ProxyZoneSpec.get();
  860. ProxyZoneSpec.assertPresent();
  861. // We need to create the AsyncTestZoneSpec outside the ProxyZone.
  862. // If we do it in ProxyZone then we will get to infinite recursion.
  863. var proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
  864. var previousDelegate = proxyZoneSpec.getDelegate();
  865. proxyZone.parent.run(function () {
  866. var testZoneSpec = new AsyncTestZoneSpec(function () {
  867. // Need to restore the original zone.
  868. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  869. // Only reset the zone spec if it's
  870. // sill this one. Otherwise, assume
  871. // it's OK.
  872. proxyZoneSpec.setDelegate(previousDelegate);
  873. }
  874. testZoneSpec.unPatchPromiseForTest();
  875. currentZone.run(function () {
  876. finishCallback();
  877. });
  878. }, function (error) {
  879. // Need to restore the original zone.
  880. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  881. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  882. proxyZoneSpec.setDelegate(previousDelegate);
  883. }
  884. testZoneSpec.unPatchPromiseForTest();
  885. currentZone.run(function () {
  886. failCallback(error);
  887. });
  888. }, 'test');
  889. proxyZoneSpec.setDelegate(testZoneSpec);
  890. testZoneSpec.patchPromiseForTest();
  891. });
  892. return Zone.current.runGuarded(fn, context);
  893. }
  894. });
  895. /**
  896. * @license
  897. * Copyright Google Inc. All Rights Reserved.
  898. *
  899. * Use of this source code is governed by an MIT-style license that can be
  900. * found in the LICENSE file at https://angular.io/license
  901. */
  902. var __read = (undefined && undefined.__read) || function (o, n) {
  903. var m = typeof Symbol === "function" && o[Symbol.iterator];
  904. if (!m) return o;
  905. var i = m.call(o), r, ar = [], e;
  906. try {
  907. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  908. }
  909. catch (error) { e = { error: error }; }
  910. finally {
  911. try {
  912. if (r && !r.done && (m = i["return"])) m.call(i);
  913. }
  914. finally { if (e) throw e.error; }
  915. }
  916. return ar;
  917. };
  918. var __spread = (undefined && undefined.__spread) || function () {
  919. for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
  920. return ar;
  921. };
  922. (function (global) {
  923. var OriginalDate = global.Date;
  924. var FakeDate = /** @class */ (function () {
  925. function FakeDate() {
  926. if (arguments.length === 0) {
  927. var d = new OriginalDate();
  928. d.setTime(FakeDate.now());
  929. return d;
  930. }
  931. else {
  932. var args = Array.prototype.slice.call(arguments);
  933. return new (OriginalDate.bind.apply(OriginalDate, __spread([void 0], args)))();
  934. }
  935. }
  936. FakeDate.now = function () {
  937. var fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  938. if (fakeAsyncTestZoneSpec) {
  939. return fakeAsyncTestZoneSpec.getCurrentRealTime() + fakeAsyncTestZoneSpec.getCurrentTime();
  940. }
  941. return OriginalDate.now.apply(this, arguments);
  942. };
  943. return FakeDate;
  944. }());
  945. FakeDate.UTC = OriginalDate.UTC;
  946. FakeDate.parse = OriginalDate.parse;
  947. // keep a reference for zone patched timer function
  948. var timers = {
  949. setTimeout: global.setTimeout,
  950. setInterval: global.setInterval,
  951. clearTimeout: global.clearTimeout,
  952. clearInterval: global.clearInterval
  953. };
  954. var Scheduler = /** @class */ (function () {
  955. function Scheduler() {
  956. // Scheduler queue with the tuple of end time and callback function - sorted by end time.
  957. this._schedulerQueue = [];
  958. // Current simulated time in millis.
  959. this._currentTime = 0;
  960. // Current real time in millis.
  961. this._currentRealTime = OriginalDate.now();
  962. }
  963. Scheduler.prototype.getCurrentTime = function () {
  964. return this._currentTime;
  965. };
  966. Scheduler.prototype.getCurrentRealTime = function () {
  967. return this._currentRealTime;
  968. };
  969. Scheduler.prototype.setCurrentRealTime = function (realTime) {
  970. this._currentRealTime = realTime;
  971. };
  972. Scheduler.prototype.scheduleFunction = function (cb, delay, args, isPeriodic, isRequestAnimationFrame, id) {
  973. if (args === void 0) { args = []; }
  974. if (isPeriodic === void 0) { isPeriodic = false; }
  975. if (isRequestAnimationFrame === void 0) { isRequestAnimationFrame = false; }
  976. if (id === void 0) { id = -1; }
  977. var currentId = id < 0 ? Scheduler.nextId++ : id;
  978. var endTime = this._currentTime + delay;
  979. // Insert so that scheduler queue remains sorted by end time.
  980. var newEntry = {
  981. endTime: endTime,
  982. id: currentId,
  983. func: cb,
  984. args: args,
  985. delay: delay,
  986. isPeriodic: isPeriodic,
  987. isRequestAnimationFrame: isRequestAnimationFrame
  988. };
  989. var i = 0;
  990. for (; i < this._schedulerQueue.length; i++) {
  991. var currentEntry = this._schedulerQueue[i];
  992. if (newEntry.endTime < currentEntry.endTime) {
  993. break;
  994. }
  995. }
  996. this._schedulerQueue.splice(i, 0, newEntry);
  997. return currentId;
  998. };
  999. Scheduler.prototype.removeScheduledFunctionWithId = function (id) {
  1000. for (var i = 0; i < this._schedulerQueue.length; i++) {
  1001. if (this._schedulerQueue[i].id == id) {
  1002. this._schedulerQueue.splice(i, 1);
  1003. break;
  1004. }
  1005. }
  1006. };
  1007. Scheduler.prototype.tick = function (millis, doTick) {
  1008. if (millis === void 0) { millis = 0; }
  1009. var finalTime = this._currentTime + millis;
  1010. var lastCurrentTime = 0;
  1011. if (this._schedulerQueue.length === 0 && doTick) {
  1012. doTick(millis);
  1013. return;
  1014. }
  1015. while (this._schedulerQueue.length > 0) {
  1016. var current = this._schedulerQueue[0];
  1017. if (finalTime < current.endTime) {
  1018. // Done processing the queue since it's sorted by endTime.
  1019. break;
  1020. }
  1021. else {
  1022. // Time to run scheduled function. Remove it from the head of queue.
  1023. var current_1 = this._schedulerQueue.shift();
  1024. lastCurrentTime = this._currentTime;
  1025. this._currentTime = current_1.endTime;
  1026. if (doTick) {
  1027. doTick(this._currentTime - lastCurrentTime);
  1028. }
  1029. var retval = current_1.func.apply(global, current_1.isRequestAnimationFrame ? [this._currentTime] : current_1.args);
  1030. if (!retval) {
  1031. // Uncaught exception in the current scheduled function. Stop processing the queue.
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. lastCurrentTime = this._currentTime;
  1037. this._currentTime = finalTime;
  1038. if (doTick) {
  1039. doTick(this._currentTime - lastCurrentTime);
  1040. }
  1041. };
  1042. Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
  1043. if (limit === void 0) { limit = 20; }
  1044. if (flushPeriodic === void 0) { flushPeriodic = false; }
  1045. if (flushPeriodic) {
  1046. return this.flushPeriodic(doTick);
  1047. }
  1048. else {
  1049. return this.flushNonPeriodic(limit, doTick);
  1050. }
  1051. };
  1052. Scheduler.prototype.flushPeriodic = function (doTick) {
  1053. if (this._schedulerQueue.length === 0) {
  1054. return 0;
  1055. }
  1056. // Find the last task currently queued in the scheduler queue and tick
  1057. // till that time.
  1058. var startTime = this._currentTime;
  1059. var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
  1060. this.tick(lastTask.endTime - startTime, doTick);
  1061. return this._currentTime - startTime;
  1062. };
  1063. Scheduler.prototype.flushNonPeriodic = function (limit, doTick) {
  1064. var startTime = this._currentTime;
  1065. var lastCurrentTime = 0;
  1066. var count = 0;
  1067. while (this._schedulerQueue.length > 0) {
  1068. count++;
  1069. if (count > limit) {
  1070. throw new Error('flush failed after reaching the limit of ' + limit +
  1071. ' tasks. Does your code use a polling timeout?');
  1072. }
  1073. // flush only non-periodic timers.
  1074. // If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
  1075. if (this._schedulerQueue.filter(function (task) { return !task.isPeriodic && !task.isRequestAnimationFrame; })
  1076. .length === 0) {
  1077. break;
  1078. }
  1079. var current = this._schedulerQueue.shift();
  1080. lastCurrentTime = this._currentTime;
  1081. this._currentTime = current.endTime;
  1082. if (doTick) {
  1083. // Update any secondary schedulers like Jasmine mock Date.
  1084. doTick(this._currentTime - lastCurrentTime);
  1085. }
  1086. var retval = current.func.apply(global, current.args);
  1087. if (!retval) {
  1088. // Uncaught exception in the current scheduled function. Stop processing the queue.
  1089. break;
  1090. }
  1091. }
  1092. return this._currentTime - startTime;
  1093. };
  1094. // Next scheduler id.
  1095. Scheduler.nextId = 1;
  1096. return Scheduler;
  1097. }());
  1098. var FakeAsyncTestZoneSpec = /** @class */ (function () {
  1099. function FakeAsyncTestZoneSpec(namePrefix, trackPendingRequestAnimationFrame, macroTaskOptions) {
  1100. if (trackPendingRequestAnimationFrame === void 0) { trackPendingRequestAnimationFrame = false; }
  1101. this.trackPendingRequestAnimationFrame = trackPendingRequestAnimationFrame;
  1102. this.macroTaskOptions = macroTaskOptions;
  1103. this._scheduler = new Scheduler();
  1104. this._microtasks = [];
  1105. this._lastError = null;
  1106. this._uncaughtPromiseErrors = Promise[Zone.__symbol__('uncaughtPromiseErrors')];
  1107. this.pendingPeriodicTimers = [];
  1108. this.pendingTimers = [];
  1109. this.patchDateLocked = false;
  1110. this.properties = { 'FakeAsyncTestZoneSpec': this };
  1111. this.name = 'fakeAsyncTestZone for ' + namePrefix;
  1112. // in case user can't access the construction of FakeAsyncTestSpec
  1113. // user can also define macroTaskOptions by define a global variable.
  1114. if (!this.macroTaskOptions) {
  1115. this.macroTaskOptions = global[Zone.__symbol__('FakeAsyncTestMacroTask')];
  1116. }
  1117. }
  1118. FakeAsyncTestZoneSpec.assertInZone = function () {
  1119. if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
  1120. throw new Error('The code should be running in the fakeAsync zone to call this function');
  1121. }
  1122. };
  1123. FakeAsyncTestZoneSpec.prototype._fnAndFlush = function (fn, completers) {
  1124. var _this = this;
  1125. return function () {
  1126. var args = [];
  1127. for (var _i = 0; _i < arguments.length; _i++) {
  1128. args[_i] = arguments[_i];
  1129. }
  1130. fn.apply(global, args);
  1131. if (_this._lastError === null) { // Success
  1132. if (completers.onSuccess != null) {
  1133. completers.onSuccess.apply(global);
  1134. }
  1135. // Flush microtasks only on success.
  1136. _this.flushMicrotasks();
  1137. }
  1138. else { // Failure
  1139. if (completers.onError != null) {
  1140. completers.onError.apply(global);
  1141. }
  1142. }
  1143. // Return true if there were no errors, false otherwise.
  1144. return _this._lastError === null;
  1145. };
  1146. };
  1147. FakeAsyncTestZoneSpec._removeTimer = function (timers, id) {
  1148. var index = timers.indexOf(id);
  1149. if (index > -1) {
  1150. timers.splice(index, 1);
  1151. }
  1152. };
  1153. FakeAsyncTestZoneSpec.prototype._dequeueTimer = function (id) {
  1154. var _this = this;
  1155. return function () {
  1156. FakeAsyncTestZoneSpec._removeTimer(_this.pendingTimers, id);
  1157. };
  1158. };
  1159. FakeAsyncTestZoneSpec.prototype._requeuePeriodicTimer = function (fn, interval, args, id) {
  1160. var _this = this;
  1161. return function () {
  1162. // Requeue the timer callback if it's not been canceled.
  1163. if (_this.pendingPeriodicTimers.indexOf(id) !== -1) {
  1164. _this._scheduler.scheduleFunction(fn, interval, args, true, false, id);
  1165. }
  1166. };
  1167. };
  1168. FakeAsyncTestZoneSpec.prototype._dequeuePeriodicTimer = function (id) {
  1169. var _this = this;
  1170. return function () {
  1171. FakeAsyncTestZoneSpec._removeTimer(_this.pendingPeriodicTimers, id);
  1172. };
  1173. };
  1174. FakeAsyncTestZoneSpec.prototype._setTimeout = function (fn, delay, args, isTimer) {
  1175. if (isTimer === void 0) { isTimer = true; }
  1176. var removeTimerFn = this._dequeueTimer(Scheduler.nextId);
  1177. // Queue the callback and dequeue the timer on success and error.
  1178. var cb = this._fnAndFlush(fn, { onSuccess: removeTimerFn, onError: removeTimerFn });
  1179. var id = this._scheduler.scheduleFunction(cb, delay, args, false, !isTimer);
  1180. if (isTimer) {
  1181. this.pendingTimers.push(id);
  1182. }
  1183. return id;
  1184. };
  1185. FakeAsyncTestZoneSpec.prototype._clearTimeout = function (id) {
  1186. FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
  1187. this._scheduler.removeScheduledFunctionWithId(id);
  1188. };
  1189. FakeAsyncTestZoneSpec.prototype._setInterval = function (fn, interval, args) {
  1190. var id = Scheduler.nextId;
  1191. var completers = { onSuccess: null, onError: this._dequeuePeriodicTimer(id) };
  1192. var cb = this._fnAndFlush(fn, completers);
  1193. // Use the callback created above to requeue on success.
  1194. completers.onSuccess = this._requeuePeriodicTimer(cb, interval, args, id);
  1195. // Queue the callback and dequeue the periodic timer only on error.
  1196. this._scheduler.scheduleFunction(cb, interval, args, true);
  1197. this.pendingPeriodicTimers.push(id);
  1198. return id;
  1199. };
  1200. FakeAsyncTestZoneSpec.prototype._clearInterval = function (id) {
  1201. FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
  1202. this._scheduler.removeScheduledFunctionWithId(id);
  1203. };
  1204. FakeAsyncTestZoneSpec.prototype._resetLastErrorAndThrow = function () {
  1205. var error = this._lastError || this._uncaughtPromiseErrors[0];
  1206. this._uncaughtPromiseErrors.length = 0;
  1207. this._lastError = null;
  1208. throw error;
  1209. };
  1210. FakeAsyncTestZoneSpec.prototype.getCurrentTime = function () {
  1211. return this._scheduler.getCurrentTime();
  1212. };
  1213. FakeAsyncTestZoneSpec.prototype.getCurrentRealTime = function () {
  1214. return this._scheduler.getCurrentRealTime();
  1215. };
  1216. FakeAsyncTestZoneSpec.prototype.setCurrentRealTime = function (realTime) {
  1217. this._scheduler.setCurrentRealTime(realTime);
  1218. };
  1219. FakeAsyncTestZoneSpec.patchDate = function () {
  1220. if (!!global[Zone.__symbol__('disableDatePatching')]) {
  1221. // we don't want to patch global Date
  1222. // because in some case, global Date
  1223. // is already being patched, we need to provide
  1224. // an option to let user still use their
  1225. // own version of Date.
  1226. return;
  1227. }
  1228. if (global['Date'] === FakeDate) {
  1229. // already patched
  1230. return;
  1231. }
  1232. global['Date'] = FakeDate;
  1233. FakeDate.prototype = OriginalDate.prototype;
  1234. // try check and reset timers
  1235. // because jasmine.clock().install() may
  1236. // have replaced the global timer
  1237. FakeAsyncTestZoneSpec.checkTimerPatch();
  1238. };
  1239. FakeAsyncTestZoneSpec.resetDate = function () {
  1240. if (global['Date'] === FakeDate) {
  1241. global['Date'] = OriginalDate;
  1242. }
  1243. };
  1244. FakeAsyncTestZoneSpec.checkTimerPatch = function () {
  1245. if (global.setTimeout !== timers.setTimeout) {
  1246. global.setTimeout = timers.setTimeout;
  1247. global.clearTimeout = timers.clearTimeout;
  1248. }
  1249. if (global.setInterval !== timers.setInterval) {
  1250. global.setInterval = timers.setInterval;
  1251. global.clearInterval = timers.clearInterval;
  1252. }
  1253. };
  1254. FakeAsyncTestZoneSpec.prototype.lockDatePatch = function () {
  1255. this.patchDateLocked = true;
  1256. FakeAsyncTestZoneSpec.patchDate();
  1257. };
  1258. FakeAsyncTestZoneSpec.prototype.unlockDatePatch = function () {
  1259. this.patchDateLocked = false;
  1260. FakeAsyncTestZoneSpec.resetDate();
  1261. };
  1262. FakeAsyncTestZoneSpec.prototype.tick = function (millis, doTick) {
  1263. if (millis === void 0) { millis = 0; }
  1264. FakeAsyncTestZoneSpec.assertInZone();
  1265. this.flushMicrotasks();
  1266. this._scheduler.tick(millis, doTick);
  1267. if (this._lastError !== null) {
  1268. this._resetLastErrorAndThrow();
  1269. }
  1270. };
  1271. FakeAsyncTestZoneSpec.prototype.flushMicrotasks = function () {
  1272. var _this = this;
  1273. FakeAsyncTestZoneSpec.assertInZone();
  1274. var flushErrors = function () {
  1275. if (_this._lastError !== null || _this._uncaughtPromiseErrors.length) {
  1276. // If there is an error stop processing the microtask queue and rethrow the error.
  1277. _this._resetLastErrorAndThrow();
  1278. }
  1279. };
  1280. while (this._microtasks.length > 0) {
  1281. var microtask = this._microtasks.shift();
  1282. microtask.func.apply(microtask.target, microtask.args);
  1283. }
  1284. flushErrors();
  1285. };
  1286. FakeAsyncTestZoneSpec.prototype.flush = function (limit, flushPeriodic, doTick) {
  1287. FakeAsyncTestZoneSpec.assertInZone();
  1288. this.flushMicrotasks();
  1289. var elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
  1290. if (this._lastError !== null) {
  1291. this._resetLastErrorAndThrow();
  1292. }
  1293. return elapsed;
  1294. };
  1295. FakeAsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  1296. switch (task.type) {
  1297. case 'microTask':
  1298. var args = task.data && task.data.args;
  1299. // should pass additional arguments to callback if have any
  1300. // currently we know process.nextTick will have such additional
  1301. // arguments
  1302. var additionalArgs = void 0;
  1303. if (args) {
  1304. var callbackIndex = task.data.cbIdx;
  1305. if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
  1306. additionalArgs = Array.prototype.slice.call(args, callbackIndex + 1);
  1307. }
  1308. }
  1309. this._microtasks.push({
  1310. func: task.invoke,
  1311. args: additionalArgs,
  1312. target: task.data && task.data.target
  1313. });
  1314. break;
  1315. case 'macroTask':
  1316. switch (task.source) {
  1317. case 'setTimeout':
  1318. task.data['handleId'] = this._setTimeout(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  1319. break;
  1320. case 'setImmediate':
  1321. task.data['handleId'] = this._setTimeout(task.invoke, 0, Array.prototype.slice.call(task.data['args'], 1));
  1322. break;
  1323. case 'setInterval':
  1324. task.data['handleId'] = this._setInterval(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  1325. break;
  1326. case 'XMLHttpRequest.send':
  1327. throw new Error('Cannot make XHRs from within a fake async test. Request URL: ' +
  1328. task.data['url']);
  1329. case 'requestAnimationFrame':
  1330. case 'webkitRequestAnimationFrame':
  1331. case 'mozRequestAnimationFrame':
  1332. // Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
  1333. // (60 frames per second)
  1334. task.data['handleId'] = this._setTimeout(task.invoke, 16, task.data['args'], this.trackPendingRequestAnimationFrame);
  1335. break;
  1336. default:
  1337. // user can define which macroTask they want to support by passing
  1338. // macroTaskOptions
  1339. var macroTaskOption = this.findMacroTaskOption(task);
  1340. if (macroTaskOption) {
  1341. var args_1 = task.data && task.data['args'];
  1342. var delay = args_1 && args_1.length > 1 ? args_1[1] : 0;
  1343. var callbackArgs = macroTaskOption.callbackArgs ? macroTaskOption.callbackArgs : args_1;
  1344. if (!!macroTaskOption.isPeriodic) {
  1345. // periodic macroTask, use setInterval to simulate
  1346. task.data['handleId'] = this._setInterval(task.invoke, delay, callbackArgs);
  1347. task.data.isPeriodic = true;
  1348. }
  1349. else {
  1350. // not periodic, use setTimeout to simulate
  1351. task.data['handleId'] = this._setTimeout(task.invoke, delay, callbackArgs);
  1352. }
  1353. break;
  1354. }
  1355. throw new Error('Unknown macroTask scheduled in fake async test: ' + task.source);
  1356. }
  1357. break;
  1358. case 'eventTask':
  1359. task = delegate.scheduleTask(target, task);
  1360. break;
  1361. }
  1362. return task;
  1363. };
  1364. FakeAsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  1365. switch (task.source) {
  1366. case 'setTimeout':
  1367. case 'requestAnimationFrame':
  1368. case 'webkitRequestAnimationFrame':
  1369. case 'mozRequestAnimationFrame':
  1370. return this._clearTimeout(task.data['handleId']);
  1371. case 'setInterval':
  1372. return this._clearInterval(task.data['handleId']);
  1373. default:
  1374. // user can define which macroTask they want to support by passing
  1375. // macroTaskOptions
  1376. var macroTaskOption = this.findMacroTaskOption(task);
  1377. if (macroTaskOption) {
  1378. var handleId = task.data['handleId'];
  1379. return macroTaskOption.isPeriodic ? this._clearInterval(handleId) :
  1380. this._clearTimeout(handleId);
  1381. }
  1382. return delegate.cancelTask(target, task);
  1383. }
  1384. };
  1385. FakeAsyncTestZoneSpec.prototype.onInvoke = function (delegate, current, target, callback, applyThis, applyArgs, source) {
  1386. try {
  1387. FakeAsyncTestZoneSpec.patchDate();
  1388. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  1389. }
  1390. finally {
  1391. if (!this.patchDateLocked) {
  1392. FakeAsyncTestZoneSpec.resetDate();
  1393. }
  1394. }
  1395. };
  1396. FakeAsyncTestZoneSpec.prototype.findMacroTaskOption = function (task) {
  1397. if (!this.macroTaskOptions) {
  1398. return null;
  1399. }
  1400. for (var i = 0; i < this.macroTaskOptions.length; i++) {
  1401. var macroTaskOption = this.macroTaskOptions[i];
  1402. if (macroTaskOption.source === task.source) {
  1403. return macroTaskOption;
  1404. }
  1405. }
  1406. return null;
  1407. };
  1408. FakeAsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  1409. this._lastError = error;
  1410. return false; // Don't propagate error to parent zone.
  1411. };
  1412. return FakeAsyncTestZoneSpec;
  1413. }());
  1414. // Export the class so that new instances can be created with proper
  1415. // constructor params.
  1416. Zone['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
  1417. })(typeof window === 'object' && window || typeof self === 'object' && self || global);
  1418. /**
  1419. * @license
  1420. * Copyright Google Inc. All Rights Reserved.
  1421. *
  1422. * Use of this source code is governed by an MIT-style license that can be
  1423. * found in the LICENSE file at https://angular.io/license
  1424. */
  1425. Zone.__load_patch('fakeasync', function (global, Zone, api) {
  1426. var FakeAsyncTestZoneSpec = Zone && Zone['FakeAsyncTestZoneSpec'];
  1427. var ProxyZoneSpec = Zone && Zone['ProxyZoneSpec'];
  1428. var _fakeAsyncTestZoneSpec = null;
  1429. /**
  1430. * Clears out the shared fake async zone for a test.
  1431. * To be called in a global `beforeEach`.
  1432. *
  1433. * @experimental
  1434. */
  1435. function resetFakeAsyncZone() {
  1436. if (_fakeAsyncTestZoneSpec) {
  1437. _fakeAsyncTestZoneSpec.unlockDatePatch();
  1438. }
  1439. _fakeAsyncTestZoneSpec = null;
  1440. // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
  1441. ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
  1442. }
  1443. /**
  1444. * Wraps a function to be executed in the fakeAsync zone:
  1445. * - microtasks are manually executed by calling `flushMicrotasks()`,
  1446. * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
  1447. *
  1448. * If there are any pending timers at the end of the function, an exception will be thrown.
  1449. *
  1450. * Can be used to wrap inject() calls.
  1451. *
  1452. * ## Example
  1453. *
  1454. * {@example core/testing/ts/fake_async.ts region='basic'}
  1455. *
  1456. * @param fn
  1457. * @returns The function wrapped to be executed in the fakeAsync zone
  1458. *
  1459. * @experimental
  1460. */
  1461. function fakeAsync(fn) {
  1462. // Not using an arrow function to preserve context passed from call site
  1463. return function () {
  1464. var args = [];
  1465. for (var _i = 0; _i < arguments.length; _i++) {
  1466. args[_i] = arguments[_i];
  1467. }
  1468. var proxyZoneSpec = ProxyZoneSpec.assertPresent();
  1469. if (Zone.current.get('FakeAsyncTestZoneSpec')) {
  1470. throw new Error('fakeAsync() calls can not be nested');
  1471. }
  1472. try {
  1473. // in case jasmine.clock init a fakeAsyncTestZoneSpec
  1474. if (!_fakeAsyncTestZoneSpec) {
  1475. if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
  1476. throw new Error('fakeAsync() calls can not be nested');
  1477. }
  1478. _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
  1479. }
  1480. var res = void 0;
  1481. var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
  1482. proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
  1483. _fakeAsyncTestZoneSpec.lockDatePatch();
  1484. try {
  1485. res = fn.apply(this, args);
  1486. flushMicrotasks();
  1487. }
  1488. finally {
  1489. proxyZoneSpec.setDelegate(lastProxyZoneSpec);
  1490. }
  1491. if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
  1492. throw new Error(_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length + " " +
  1493. "periodic timer(s) still in the queue.");
  1494. }
  1495. if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
  1496. throw new Error(_fakeAsyncTestZoneSpec.pendingTimers.length + " timer(s) still in the queue.");
  1497. }
  1498. return res;
  1499. }
  1500. finally {
  1501. resetFakeAsyncZone();
  1502. }
  1503. };
  1504. }
  1505. function _getFakeAsyncZoneSpec() {
  1506. if (_fakeAsyncTestZoneSpec == null) {
  1507. _fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  1508. if (_fakeAsyncTestZoneSpec == null) {
  1509. throw new Error('The code should be running in the fakeAsync zone to call this function');
  1510. }
  1511. }
  1512. return _fakeAsyncTestZoneSpec;
  1513. }
  1514. /**
  1515. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
  1516. *
  1517. * The microtasks queue is drained at the very start of this function and after any timer callback
  1518. * has been executed.
  1519. *
  1520. * ## Example
  1521. *
  1522. * {@example core/testing/ts/fake_async.ts region='basic'}
  1523. *
  1524. * @experimental
  1525. */
  1526. function tick(millis) {
  1527. if (millis === void 0) { millis = 0; }
  1528. _getFakeAsyncZoneSpec().tick(millis);
  1529. }
  1530. /**
  1531. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
  1532. * draining the macrotask queue until it is empty. The returned value is the milliseconds
  1533. * of time that would have been elapsed.
  1534. *
  1535. * @param maxTurns
  1536. * @returns The simulated time elapsed, in millis.
  1537. *
  1538. * @experimental
  1539. */
  1540. function flush(maxTurns) {
  1541. return _getFakeAsyncZoneSpec().flush(maxTurns);
  1542. }
  1543. /**
  1544. * Discard all remaining periodic tasks.
  1545. *
  1546. * @experimental
  1547. */
  1548. function discardPeriodicTasks() {
  1549. var zoneSpec = _getFakeAsyncZoneSpec();
  1550. var pendingTimers = zoneSpec.pendingPeriodicTimers;
  1551. zoneSpec.pendingPeriodicTimers.length = 0;
  1552. }
  1553. /**
  1554. * Flush any pending microtasks.
  1555. *
  1556. * @experimental
  1557. */
  1558. function flushMicrotasks() {
  1559. _getFakeAsyncZoneSpec().flushMicrotasks();
  1560. }
  1561. Zone[api.symbol('fakeAsyncTest')] =
  1562. { resetFakeAsyncZone: resetFakeAsyncZone, flushMicrotasks: flushMicrotasks, discardPeriodicTasks: discardPeriodicTasks, tick: tick, flush: flush, fakeAsync: fakeAsync };
  1563. });
  1564. /**
  1565. * @license
  1566. * Copyright Google Inc. All Rights Reserved.
  1567. *
  1568. * Use of this source code is governed by an MIT-style license that can be
  1569. * found in the LICENSE file at https://angular.io/license
  1570. */
  1571. /**
  1572. * Promise for async/fakeAsync zoneSpec test
  1573. * can support async operation which not supported by zone.js
  1574. * such as
  1575. * it ('test jsonp in AsyncZone', async() => {
  1576. * new Promise(res => {
  1577. * jsonp(url, (data) => {
  1578. * // success callback
  1579. * res(data);
  1580. * });
  1581. * }).then((jsonpResult) => {
  1582. * // get jsonp result.
  1583. *
  1584. * // user will expect AsyncZoneSpec wait for
  1585. * // then, but because jsonp is not zone aware
  1586. * // AsyncZone will finish before then is called.
  1587. * });
  1588. * });
  1589. */
  1590. Zone.__load_patch('promisefortest', function (global, Zone, api) {
  1591. var symbolState = api.symbol('state');
  1592. var UNRESOLVED = null;
  1593. var symbolParentUnresolved = api.symbol('parentUnresolved');
  1594. // patch Promise.prototype.then to keep an internal
  1595. // number for tracking unresolved chained promise
  1596. // we will decrease this number when the parent promise
  1597. // being resolved/rejected and chained promise was
  1598. // scheduled as a microTask.
  1599. // so we can know such kind of chained promise still
  1600. // not resolved in AsyncTestZone
  1601. Promise[api.symbol('patchPromiseForTest')] = function patchPromiseForTest() {
  1602. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  1603. if (oriThen) {
  1604. return;
  1605. }
  1606. oriThen = Promise[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
  1607. Promise.prototype.then = function () {
  1608. var chained = oriThen.apply(this, arguments);
  1609. if (this[symbolState] === UNRESOLVED) {
  1610. // parent promise is unresolved.
  1611. var asyncTestZoneSpec = Zone.current.get('AsyncTestZoneSpec');
  1612. if (asyncTestZoneSpec) {
  1613. asyncTestZoneSpec.unresolvedChainedPromiseCount++;
  1614. chained[symbolParentUnresolved] = true;
  1615. }
  1616. }
  1617. return chained;
  1618. };
  1619. };
  1620. Promise[api.symbol('unPatchPromiseForTest')] = function unpatchPromiseForTest() {
  1621. // restore origin then
  1622. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  1623. if (oriThen) {
  1624. Promise.prototype.then = oriThen;
  1625. Promise[Zone.__symbol__('ZonePromiseThen')] = undefined;
  1626. }
  1627. };
  1628. });
  1629. /**
  1630. * @license
  1631. * Copyright Google Inc. All Rights Reserved.
  1632. *
  1633. * Use of this source code is governed by an MIT-style license that can be
  1634. * found in the LICENSE file at https://angular.io/license
  1635. */
  1636. // load test related files into bundle in correct order
  1637. })));