zone-testing.umd.js 106 KB

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