zone-testing.umd.js 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223
  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. // From jest 29 and jest-preset-angular v13, the module transform logic
  705. // changed, and now jest-preset-angular use the use the tsconfig target
  706. // other than the hardcoded one, https://github.com/thymikee/jest-preset-angular/issues/2010
  707. // But jest-angular-preset doesn't introduce the @babel/plugin-transform-async-to-generator
  708. // which is needed by angular since `async/await` still need to be transformed
  709. // to promise for ES2017+ target.
  710. // So for now, we disable to output the uncaught error console log for a temp solution,
  711. // until jest-preset-angular find a proper solution.
  712. Zone[api.symbol('ignoreConsoleErrorUncaughtError')] = true;
  713. jest['__zone_patch__'] = true;
  714. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  715. var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  716. if (!ProxyZoneSpec) {
  717. throw new Error('Missing ProxyZoneSpec');
  718. }
  719. var rootZone = Zone.current;
  720. var syncZone = rootZone.fork(new SyncTestZoneSpec('jest.describe'));
  721. var proxyZoneSpec = new ProxyZoneSpec();
  722. var proxyZone = rootZone.fork(proxyZoneSpec);
  723. function wrapDescribeFactoryInZone(originalJestFn) {
  724. return function () {
  725. var tableArgs = [];
  726. for (var _i = 0; _i < arguments.length; _i++) {
  727. tableArgs[_i] = arguments[_i];
  728. }
  729. var originalDescribeFn = originalJestFn.apply(this, tableArgs);
  730. return function () {
  731. var args = [];
  732. for (var _i = 0; _i < arguments.length; _i++) {
  733. args[_i] = arguments[_i];
  734. }
  735. args[1] = wrapDescribeInZone(args[1]);
  736. return originalDescribeFn.apply(this, args);
  737. };
  738. };
  739. }
  740. function wrapTestFactoryInZone(originalJestFn) {
  741. return function () {
  742. var tableArgs = [];
  743. for (var _i = 0; _i < arguments.length; _i++) {
  744. tableArgs[_i] = arguments[_i];
  745. }
  746. return function () {
  747. var args = [];
  748. for (var _i = 0; _i < arguments.length; _i++) {
  749. args[_i] = arguments[_i];
  750. }
  751. args[1] = wrapTestInZone(args[1]);
  752. return originalJestFn.apply(this, tableArgs).apply(this, args);
  753. };
  754. };
  755. }
  756. /**
  757. * Gets a function wrapping the body of a jest `describe` block to execute in a
  758. * synchronous-only zone.
  759. */
  760. function wrapDescribeInZone(describeBody) {
  761. return function () {
  762. var args = [];
  763. for (var _i = 0; _i < arguments.length; _i++) {
  764. args[_i] = arguments[_i];
  765. }
  766. return syncZone.run(describeBody, this, args);
  767. };
  768. }
  769. /**
  770. * Gets a function wrapping the body of a jest `it/beforeEach/afterEach` block to
  771. * execute in a ProxyZone zone.
  772. * This will run in the `proxyZone`.
  773. */
  774. function wrapTestInZone(testBody, isTestFunc) {
  775. if (isTestFunc === void 0) { isTestFunc = false; }
  776. if (typeof testBody !== 'function') {
  777. return testBody;
  778. }
  779. var wrappedFunc = function () {
  780. if (Zone[api.symbol('useFakeTimersCalled')] === true && testBody &&
  781. !testBody.isFakeAsync) {
  782. // jest.useFakeTimers is called, run into fakeAsyncTest automatically.
  783. var fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
  784. if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
  785. testBody = fakeAsyncModule.fakeAsync(testBody);
  786. }
  787. }
  788. proxyZoneSpec.isTestFunc = isTestFunc;
  789. return proxyZone.run(testBody, null, arguments);
  790. };
  791. // Update the length of wrappedFunc to be the same as the length of the testBody
  792. // So jest core can handle whether the test function has `done()` or not correctly
  793. Object.defineProperty(wrappedFunc, 'length', { configurable: true, writable: true, enumerable: false });
  794. wrappedFunc.length = testBody.length;
  795. return wrappedFunc;
  796. }
  797. ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
  798. var originalJestFn = context[methodName];
  799. if (context[Zone.__symbol__(methodName)]) {
  800. return;
  801. }
  802. context[Zone.__symbol__(methodName)] = originalJestFn;
  803. context[methodName] = function () {
  804. var args = [];
  805. for (var _i = 0; _i < arguments.length; _i++) {
  806. args[_i] = arguments[_i];
  807. }
  808. args[1] = wrapDescribeInZone(args[1]);
  809. return originalJestFn.apply(this, args);
  810. };
  811. context[methodName].each = wrapDescribeFactoryInZone(originalJestFn.each);
  812. });
  813. context.describe.only = context.fdescribe;
  814. context.describe.skip = context.xdescribe;
  815. ['it', 'xit', 'fit', 'test', 'xtest'].forEach(function (methodName) {
  816. var originalJestFn = context[methodName];
  817. if (context[Zone.__symbol__(methodName)]) {
  818. return;
  819. }
  820. context[Zone.__symbol__(methodName)] = originalJestFn;
  821. context[methodName] = function () {
  822. var args = [];
  823. for (var _i = 0; _i < arguments.length; _i++) {
  824. args[_i] = arguments[_i];
  825. }
  826. args[1] = wrapTestInZone(args[1], true);
  827. return originalJestFn.apply(this, args);
  828. };
  829. context[methodName].each = wrapTestFactoryInZone(originalJestFn.each);
  830. context[methodName].todo = originalJestFn.todo;
  831. });
  832. context.it.only = context.fit;
  833. context.it.skip = context.xit;
  834. context.test.only = context.fit;
  835. context.test.skip = context.xit;
  836. ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(function (methodName) {
  837. var originalJestFn = context[methodName];
  838. if (context[Zone.__symbol__(methodName)]) {
  839. return;
  840. }
  841. context[Zone.__symbol__(methodName)] = originalJestFn;
  842. context[methodName] = function () {
  843. var args = [];
  844. for (var _i = 0; _i < arguments.length; _i++) {
  845. args[_i] = arguments[_i];
  846. }
  847. args[0] = wrapTestInZone(args[0]);
  848. return originalJestFn.apply(this, args);
  849. };
  850. });
  851. Zone.patchJestObject = function patchJestObject(Timer, isModern) {
  852. if (isModern === void 0) { isModern = false; }
  853. // check whether currently the test is inside fakeAsync()
  854. function isPatchingFakeTimer() {
  855. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  856. return !!fakeAsyncZoneSpec;
  857. }
  858. // check whether the current function is inside `test/it` or other methods
  859. // such as `describe/beforeEach`
  860. function isInTestFunc() {
  861. var proxyZoneSpec = Zone.current.get('ProxyZoneSpec');
  862. return proxyZoneSpec && proxyZoneSpec.isTestFunc;
  863. }
  864. if (Timer[api.symbol('fakeTimers')]) {
  865. return;
  866. }
  867. Timer[api.symbol('fakeTimers')] = true;
  868. // patch jest fakeTimer internal method to make sure no console.warn print out
  869. api.patchMethod(Timer, '_checkFakeTimers', function (delegate) {
  870. return function (self, args) {
  871. if (isPatchingFakeTimer()) {
  872. return true;
  873. }
  874. else {
  875. return delegate.apply(self, args);
  876. }
  877. };
  878. });
  879. // patch useFakeTimers(), set useFakeTimersCalled flag, and make test auto run into fakeAsync
  880. api.patchMethod(Timer, 'useFakeTimers', function (delegate) {
  881. return function (self, args) {
  882. Zone[api.symbol('useFakeTimersCalled')] = true;
  883. if (isModern || isInTestFunc()) {
  884. return delegate.apply(self, args);
  885. }
  886. return self;
  887. };
  888. });
  889. // patch useRealTimers(), unset useFakeTimers flag
  890. api.patchMethod(Timer, 'useRealTimers', function (delegate) {
  891. return function (self, args) {
  892. Zone[api.symbol('useFakeTimersCalled')] = false;
  893. if (isModern || isInTestFunc()) {
  894. return delegate.apply(self, args);
  895. }
  896. return self;
  897. };
  898. });
  899. // patch setSystemTime(), call setCurrentRealTime() in the fakeAsyncTest
  900. api.patchMethod(Timer, 'setSystemTime', function (delegate) {
  901. return function (self, args) {
  902. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  903. if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
  904. fakeAsyncZoneSpec.setFakeBaseSystemTime(args[0]);
  905. }
  906. else {
  907. return delegate.apply(self, args);
  908. }
  909. };
  910. });
  911. // patch getSystemTime(), call getCurrentRealTime() in the fakeAsyncTest
  912. api.patchMethod(Timer, 'getRealSystemTime', function (delegate) {
  913. return function (self, args) {
  914. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  915. if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
  916. return fakeAsyncZoneSpec.getRealSystemTime();
  917. }
  918. else {
  919. return delegate.apply(self, args);
  920. }
  921. };
  922. });
  923. // patch runAllTicks(), run all microTasks inside fakeAsync
  924. api.patchMethod(Timer, 'runAllTicks', function (delegate) {
  925. return function (self, args) {
  926. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  927. if (fakeAsyncZoneSpec) {
  928. fakeAsyncZoneSpec.flushMicrotasks();
  929. }
  930. else {
  931. return delegate.apply(self, args);
  932. }
  933. };
  934. });
  935. // patch runAllTimers(), run all macroTasks inside fakeAsync
  936. api.patchMethod(Timer, 'runAllTimers', function (delegate) {
  937. return function (self, args) {
  938. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  939. if (fakeAsyncZoneSpec) {
  940. fakeAsyncZoneSpec.flush(100, true);
  941. }
  942. else {
  943. return delegate.apply(self, args);
  944. }
  945. };
  946. });
  947. // patch advanceTimersByTime(), call tick() in the fakeAsyncTest
  948. api.patchMethod(Timer, 'advanceTimersByTime', function (delegate) {
  949. return function (self, args) {
  950. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  951. if (fakeAsyncZoneSpec) {
  952. fakeAsyncZoneSpec.tick(args[0]);
  953. }
  954. else {
  955. return delegate.apply(self, args);
  956. }
  957. };
  958. });
  959. // patch runOnlyPendingTimers(), call flushOnlyPendingTimers() in the fakeAsyncTest
  960. api.patchMethod(Timer, 'runOnlyPendingTimers', function (delegate) {
  961. return function (self, args) {
  962. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  963. if (fakeAsyncZoneSpec) {
  964. fakeAsyncZoneSpec.flushOnlyPendingTimers();
  965. }
  966. else {
  967. return delegate.apply(self, args);
  968. }
  969. };
  970. });
  971. // patch advanceTimersToNextTimer(), call tickToNext() in the fakeAsyncTest
  972. api.patchMethod(Timer, 'advanceTimersToNextTimer', function (delegate) {
  973. return function (self, args) {
  974. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  975. if (fakeAsyncZoneSpec) {
  976. fakeAsyncZoneSpec.tickToNext(args[0]);
  977. }
  978. else {
  979. return delegate.apply(self, args);
  980. }
  981. };
  982. });
  983. // patch clearAllTimers(), call removeAllTimers() in the fakeAsyncTest
  984. api.patchMethod(Timer, 'clearAllTimers', function (delegate) {
  985. return function (self, args) {
  986. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  987. if (fakeAsyncZoneSpec) {
  988. fakeAsyncZoneSpec.removeAllTimers();
  989. }
  990. else {
  991. return delegate.apply(self, args);
  992. }
  993. };
  994. });
  995. // patch getTimerCount(), call getTimerCount() in the fakeAsyncTest
  996. api.patchMethod(Timer, 'getTimerCount', function (delegate) {
  997. return function (self, args) {
  998. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  999. if (fakeAsyncZoneSpec) {
  1000. return fakeAsyncZoneSpec.getTimerCount();
  1001. }
  1002. else {
  1003. return delegate.apply(self, args);
  1004. }
  1005. };
  1006. });
  1007. };
  1008. });
  1009. Zone.__load_patch('mocha', function (global, Zone) {
  1010. var Mocha = global.Mocha;
  1011. if (typeof Mocha === 'undefined') {
  1012. // return if Mocha is not available, because now zone-testing
  1013. // will load mocha patch with jasmine/jest patch
  1014. return;
  1015. }
  1016. if (typeof Zone === 'undefined') {
  1017. throw new Error('Missing Zone.js');
  1018. }
  1019. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  1020. var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  1021. if (!ProxyZoneSpec) {
  1022. throw new Error('Missing ProxyZoneSpec');
  1023. }
  1024. if (Mocha['__zone_patch__']) {
  1025. throw new Error('"Mocha" has already been patched with "Zone".');
  1026. }
  1027. Mocha['__zone_patch__'] = true;
  1028. var rootZone = Zone.current;
  1029. var syncZone = rootZone.fork(new SyncTestZoneSpec('Mocha.describe'));
  1030. var testZone = null;
  1031. var suiteZone = rootZone.fork(new ProxyZoneSpec());
  1032. var mochaOriginal = {
  1033. after: global.after,
  1034. afterEach: global.afterEach,
  1035. before: global.before,
  1036. beforeEach: global.beforeEach,
  1037. describe: global.describe,
  1038. it: global.it
  1039. };
  1040. function modifyArguments(args, syncTest, asyncTest) {
  1041. var _loop_1 = function (i) {
  1042. var arg = args[i];
  1043. if (typeof arg === 'function') {
  1044. // The `done` callback is only passed through if the function expects at
  1045. // least one argument.
  1046. // Note we have to make a function with correct number of arguments,
  1047. // otherwise mocha will
  1048. // think that all functions are sync or async.
  1049. args[i] = (arg.length === 0) ? syncTest(arg) : asyncTest(arg);
  1050. // Mocha uses toString to view the test body in the result list, make sure we return the
  1051. // correct function body
  1052. args[i].toString = function () {
  1053. return arg.toString();
  1054. };
  1055. }
  1056. };
  1057. for (var i = 0; i < args.length; i++) {
  1058. _loop_1(i);
  1059. }
  1060. return args;
  1061. }
  1062. function wrapDescribeInZone(args) {
  1063. var syncTest = function (fn) {
  1064. return function () {
  1065. return syncZone.run(fn, this, arguments);
  1066. };
  1067. };
  1068. return modifyArguments(args, syncTest);
  1069. }
  1070. function wrapTestInZone(args) {
  1071. var asyncTest = function (fn) {
  1072. return function (done) {
  1073. return testZone.run(fn, this, [done]);
  1074. };
  1075. };
  1076. var syncTest = function (fn) {
  1077. return function () {
  1078. return testZone.run(fn, this);
  1079. };
  1080. };
  1081. return modifyArguments(args, syncTest, asyncTest);
  1082. }
  1083. function wrapSuiteInZone(args) {
  1084. var asyncTest = function (fn) {
  1085. return function (done) {
  1086. return suiteZone.run(fn, this, [done]);
  1087. };
  1088. };
  1089. var syncTest = function (fn) {
  1090. return function () {
  1091. return suiteZone.run(fn, this);
  1092. };
  1093. };
  1094. return modifyArguments(args, syncTest, asyncTest);
  1095. }
  1096. global.describe = global.suite = function () {
  1097. return mochaOriginal.describe.apply(this, wrapDescribeInZone(arguments));
  1098. };
  1099. global.xdescribe = global.suite.skip = global.describe.skip = function () {
  1100. return mochaOriginal.describe.skip.apply(this, wrapDescribeInZone(arguments));
  1101. };
  1102. global.describe.only = global.suite.only = function () {
  1103. return mochaOriginal.describe.only.apply(this, wrapDescribeInZone(arguments));
  1104. };
  1105. global.it = global.specify = global.test = function () {
  1106. return mochaOriginal.it.apply(this, wrapTestInZone(arguments));
  1107. };
  1108. global.xit = global.xspecify = global.it.skip = function () {
  1109. return mochaOriginal.it.skip.apply(this, wrapTestInZone(arguments));
  1110. };
  1111. global.it.only = global.test.only = function () {
  1112. return mochaOriginal.it.only.apply(this, wrapTestInZone(arguments));
  1113. };
  1114. global.after = global.suiteTeardown = function () {
  1115. return mochaOriginal.after.apply(this, wrapSuiteInZone(arguments));
  1116. };
  1117. global.afterEach = global.teardown = function () {
  1118. return mochaOriginal.afterEach.apply(this, wrapTestInZone(arguments));
  1119. };
  1120. global.before = global.suiteSetup = function () {
  1121. return mochaOriginal.before.apply(this, wrapSuiteInZone(arguments));
  1122. };
  1123. global.beforeEach = global.setup = function () {
  1124. return mochaOriginal.beforeEach.apply(this, wrapTestInZone(arguments));
  1125. };
  1126. (function (originalRunTest, originalRun) {
  1127. Mocha.Runner.prototype.runTest = function (fn) {
  1128. var _this = this;
  1129. Zone.current.scheduleMicroTask('mocha.forceTask', function () {
  1130. originalRunTest.call(_this, fn);
  1131. });
  1132. };
  1133. Mocha.Runner.prototype.run = function (fn) {
  1134. this.on('test', function (e) {
  1135. testZone = rootZone.fork(new ProxyZoneSpec());
  1136. });
  1137. this.on('fail', function (test, err) {
  1138. var proxyZoneSpec = testZone && testZone.get('ProxyZoneSpec');
  1139. if (proxyZoneSpec && err) {
  1140. try {
  1141. // try catch here in case err.message is not writable
  1142. err.message += proxyZoneSpec.getAndClearPendingTasksInfo();
  1143. }
  1144. catch (error) {
  1145. }
  1146. }
  1147. });
  1148. return originalRun.call(this, fn);
  1149. };
  1150. })(Mocha.Runner.prototype.runTest, Mocha.Runner.prototype.run);
  1151. });
  1152. (function (_global) {
  1153. var _a;
  1154. var AsyncTestZoneSpec = /** @class */ (function () {
  1155. function AsyncTestZoneSpec(finishCallback, failCallback, namePrefix) {
  1156. this.finishCallback = finishCallback;
  1157. this.failCallback = failCallback;
  1158. this._pendingMicroTasks = false;
  1159. this._pendingMacroTasks = false;
  1160. this._alreadyErrored = false;
  1161. this._isSync = false;
  1162. this._existingFinishTimer = null;
  1163. this.entryFunction = null;
  1164. this.runZone = Zone.current;
  1165. this.unresolvedChainedPromiseCount = 0;
  1166. this.supportWaitUnresolvedChainedPromise = false;
  1167. this.name = 'asyncTestZone for ' + namePrefix;
  1168. this.properties = { 'AsyncTestZoneSpec': this };
  1169. this.supportWaitUnresolvedChainedPromise =
  1170. _global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] === true;
  1171. }
  1172. AsyncTestZoneSpec.prototype.isUnresolvedChainedPromisePending = function () {
  1173. return this.unresolvedChainedPromiseCount > 0;
  1174. };
  1175. AsyncTestZoneSpec.prototype._finishCallbackIfDone = function () {
  1176. var _this = this;
  1177. // NOTE: Technically the `onHasTask` could fire together with the initial synchronous
  1178. // completion in `onInvoke`. `onHasTask` might call this method when it captured e.g.
  1179. // microtasks in the proxy zone that now complete as part of this async zone run.
  1180. // Consider the following scenario:
  1181. // 1. A test `beforeEach` schedules a microtask in the ProxyZone.
  1182. // 2. An actual empty `it` spec executes in the AsyncTestZone` (using e.g. `waitForAsync`).
  1183. // 3. The `onInvoke` invokes `_finishCallbackIfDone` because the spec runs synchronously.
  1184. // 4. We wait the scheduled timeout (see below) to account for unhandled promises.
  1185. // 5. The microtask from (1) finishes and `onHasTask` is invoked.
  1186. // --> We register a second `_finishCallbackIfDone` even though we have scheduled a timeout.
  1187. // If the finish timeout from below is already scheduled, terminate the existing scheduled
  1188. // finish invocation, avoiding calling `jasmine` `done` multiple times. *Note* that we would
  1189. // want to schedule a new finish callback in case the task state changes again.
  1190. if (this._existingFinishTimer !== null) {
  1191. clearTimeout(this._existingFinishTimer);
  1192. this._existingFinishTimer = null;
  1193. }
  1194. if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
  1195. (this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending()))) {
  1196. // We wait until the next tick because we would like to catch unhandled promises which could
  1197. // cause test logic to be executed. In such cases we cannot finish with tasks pending then.
  1198. this.runZone.run(function () {
  1199. _this._existingFinishTimer = setTimeout(function () {
  1200. if (!_this._alreadyErrored && !(_this._pendingMicroTasks || _this._pendingMacroTasks)) {
  1201. _this.finishCallback();
  1202. }
  1203. }, 0);
  1204. });
  1205. }
  1206. };
  1207. AsyncTestZoneSpec.prototype.patchPromiseForTest = function () {
  1208. if (!this.supportWaitUnresolvedChainedPromise) {
  1209. return;
  1210. }
  1211. var patchPromiseForTest = Promise[Zone.__symbol__('patchPromiseForTest')];
  1212. if (patchPromiseForTest) {
  1213. patchPromiseForTest();
  1214. }
  1215. };
  1216. AsyncTestZoneSpec.prototype.unPatchPromiseForTest = function () {
  1217. if (!this.supportWaitUnresolvedChainedPromise) {
  1218. return;
  1219. }
  1220. var unPatchPromiseForTest = Promise[Zone.__symbol__('unPatchPromiseForTest')];
  1221. if (unPatchPromiseForTest) {
  1222. unPatchPromiseForTest();
  1223. }
  1224. };
  1225. AsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  1226. if (task.type !== 'eventTask') {
  1227. this._isSync = false;
  1228. }
  1229. if (task.type === 'microTask' && task.data && task.data instanceof Promise) {
  1230. // check whether the promise is a chained promise
  1231. if (task.data[_a.symbolParentUnresolved] === true) {
  1232. // chained promise is being scheduled
  1233. this.unresolvedChainedPromiseCount--;
  1234. }
  1235. }
  1236. return delegate.scheduleTask(target, task);
  1237. };
  1238. AsyncTestZoneSpec.prototype.onInvokeTask = function (delegate, current, target, task, applyThis, applyArgs) {
  1239. if (task.type !== 'eventTask') {
  1240. this._isSync = false;
  1241. }
  1242. return delegate.invokeTask(target, task, applyThis, applyArgs);
  1243. };
  1244. AsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  1245. if (task.type !== 'eventTask') {
  1246. this._isSync = false;
  1247. }
  1248. return delegate.cancelTask(target, task);
  1249. };
  1250. // Note - we need to use onInvoke at the moment to call finish when a test is
  1251. // fully synchronous. TODO(juliemr): remove this when the logic for
  1252. // onHasTask changes and it calls whenever the task queues are dirty.
  1253. // updated by(JiaLiPassion), only call finish callback when no task
  1254. // was scheduled/invoked/canceled.
  1255. AsyncTestZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  1256. if (!this.entryFunction) {
  1257. this.entryFunction = delegate;
  1258. }
  1259. try {
  1260. this._isSync = true;
  1261. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  1262. }
  1263. finally {
  1264. // We need to check the delegate is the same as entryFunction or not.
  1265. // Consider the following case.
  1266. //
  1267. // asyncTestZone.run(() => { // Here the delegate will be the entryFunction
  1268. // Zone.current.run(() => { // Here the delegate will not be the entryFunction
  1269. // });
  1270. // });
  1271. //
  1272. // We only want to check whether there are async tasks scheduled
  1273. // for the entry function.
  1274. if (this._isSync && this.entryFunction === delegate) {
  1275. this._finishCallbackIfDone();
  1276. }
  1277. }
  1278. };
  1279. AsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  1280. // Let the parent try to handle the error.
  1281. var result = parentZoneDelegate.handleError(targetZone, error);
  1282. if (result) {
  1283. this.failCallback(error);
  1284. this._alreadyErrored = true;
  1285. }
  1286. return false;
  1287. };
  1288. AsyncTestZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  1289. delegate.hasTask(target, hasTaskState);
  1290. // We should only trigger finishCallback when the target zone is the AsyncTestZone
  1291. // Consider the following cases.
  1292. //
  1293. // const childZone = asyncTestZone.fork({
  1294. // name: 'child',
  1295. // onHasTask: ...
  1296. // });
  1297. //
  1298. // So we have nested zones declared the onHasTask hook, in this case,
  1299. // the onHasTask will be triggered twice, and cause the finishCallbackIfDone()
  1300. // is also be invoked twice. So we need to only trigger the finishCallbackIfDone()
  1301. // when the current zone is the same as the target zone.
  1302. if (current !== target) {
  1303. return;
  1304. }
  1305. if (hasTaskState.change == 'microTask') {
  1306. this._pendingMicroTasks = hasTaskState.microTask;
  1307. this._finishCallbackIfDone();
  1308. }
  1309. else if (hasTaskState.change == 'macroTask') {
  1310. this._pendingMacroTasks = hasTaskState.macroTask;
  1311. this._finishCallbackIfDone();
  1312. }
  1313. };
  1314. return AsyncTestZoneSpec;
  1315. }());
  1316. _a = AsyncTestZoneSpec;
  1317. (function () {
  1318. _a.symbolParentUnresolved = Zone.__symbol__('parentUnresolved');
  1319. })();
  1320. // Export the class so that new instances can be created with proper
  1321. // constructor params.
  1322. Zone['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
  1323. })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
  1324. Zone.__load_patch('asynctest', function (global, Zone, api) {
  1325. /**
  1326. * Wraps a test function in an asynchronous test zone. The test will automatically
  1327. * complete when all asynchronous calls within this zone are done.
  1328. */
  1329. Zone[api.symbol('asyncTest')] = function asyncTest(fn) {
  1330. // If we're running using the Jasmine test framework, adapt to call the 'done'
  1331. // function when asynchronous activity is finished.
  1332. if (global.jasmine) {
  1333. // Not using an arrow function to preserve context passed from call site
  1334. return function (done) {
  1335. if (!done) {
  1336. // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
  1337. // fake it here and assume sync.
  1338. done = function () { };
  1339. done.fail = function (e) {
  1340. throw e;
  1341. };
  1342. }
  1343. runInTestZone(fn, this, done, function (err) {
  1344. if (typeof err === 'string') {
  1345. return done.fail(new Error(err));
  1346. }
  1347. else {
  1348. done.fail(err);
  1349. }
  1350. });
  1351. };
  1352. }
  1353. // Otherwise, return a promise which will resolve when asynchronous activity
  1354. // is finished. This will be correctly consumed by the Mocha framework with
  1355. // it('...', async(myFn)); or can be used in a custom framework.
  1356. // Not using an arrow function to preserve context passed from call site
  1357. return function () {
  1358. var _this = this;
  1359. return new Promise(function (finishCallback, failCallback) {
  1360. runInTestZone(fn, _this, finishCallback, failCallback);
  1361. });
  1362. };
  1363. };
  1364. function runInTestZone(fn, context, finishCallback, failCallback) {
  1365. var currentZone = Zone.current;
  1366. var AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
  1367. if (AsyncTestZoneSpec === undefined) {
  1368. throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
  1369. 'Please make sure that your environment includes zone.js/plugins/async-test');
  1370. }
  1371. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  1372. if (!ProxyZoneSpec) {
  1373. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  1374. 'Please make sure that your environment includes zone.js/plugins/proxy');
  1375. }
  1376. var proxyZoneSpec = ProxyZoneSpec.get();
  1377. ProxyZoneSpec.assertPresent();
  1378. // We need to create the AsyncTestZoneSpec outside the ProxyZone.
  1379. // If we do it in ProxyZone then we will get to infinite recursion.
  1380. var proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
  1381. var previousDelegate = proxyZoneSpec.getDelegate();
  1382. proxyZone.parent.run(function () {
  1383. var testZoneSpec = new AsyncTestZoneSpec(function () {
  1384. // Need to restore the original zone.
  1385. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  1386. // Only reset the zone spec if it's
  1387. // still this one. Otherwise, assume
  1388. // it's OK.
  1389. proxyZoneSpec.setDelegate(previousDelegate);
  1390. }
  1391. testZoneSpec.unPatchPromiseForTest();
  1392. currentZone.run(function () {
  1393. finishCallback();
  1394. });
  1395. }, function (error) {
  1396. // Need to restore the original zone.
  1397. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  1398. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  1399. proxyZoneSpec.setDelegate(previousDelegate);
  1400. }
  1401. testZoneSpec.unPatchPromiseForTest();
  1402. currentZone.run(function () {
  1403. failCallback(error);
  1404. });
  1405. }, 'test');
  1406. proxyZoneSpec.setDelegate(testZoneSpec);
  1407. testZoneSpec.patchPromiseForTest();
  1408. });
  1409. return Zone.current.runGuarded(fn, context);
  1410. }
  1411. });
  1412. (function (global) {
  1413. var _a;
  1414. var OriginalDate = global.Date;
  1415. // Since when we compile this file to `es2015`, and if we define
  1416. // this `FakeDate` as `class FakeDate`, and then set `FakeDate.prototype`
  1417. // there will be an error which is `Cannot assign to read only property 'prototype'`
  1418. // so we need to use function implementation here.
  1419. function FakeDate() {
  1420. if (arguments.length === 0) {
  1421. var d = new OriginalDate();
  1422. d.setTime(FakeDate.now());
  1423. return d;
  1424. }
  1425. else {
  1426. var args = Array.prototype.slice.call(arguments);
  1427. return new (OriginalDate.bind.apply(OriginalDate, __spreadArray([void 0], args, false)))();
  1428. }
  1429. }
  1430. FakeDate.now = function () {
  1431. var fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  1432. if (fakeAsyncTestZoneSpec) {
  1433. return fakeAsyncTestZoneSpec.getFakeSystemTime();
  1434. }
  1435. return OriginalDate.now.apply(this, arguments);
  1436. };
  1437. FakeDate.UTC = OriginalDate.UTC;
  1438. FakeDate.parse = OriginalDate.parse;
  1439. // keep a reference for zone patched timer function
  1440. var timers = {
  1441. setTimeout: global.setTimeout,
  1442. setInterval: global.setInterval,
  1443. clearTimeout: global.clearTimeout,
  1444. clearInterval: global.clearInterval
  1445. };
  1446. var Scheduler = /** @class */ (function () {
  1447. function Scheduler() {
  1448. // Scheduler queue with the tuple of end time and callback function - sorted by end time.
  1449. this._schedulerQueue = [];
  1450. // Current simulated time in millis.
  1451. this._currentTickTime = 0;
  1452. // Current fake system base time in millis.
  1453. this._currentFakeBaseSystemTime = OriginalDate.now();
  1454. // track requeuePeriodicTimer
  1455. this._currentTickRequeuePeriodicEntries = [];
  1456. }
  1457. Scheduler.prototype.getCurrentTickTime = function () {
  1458. return this._currentTickTime;
  1459. };
  1460. Scheduler.prototype.getFakeSystemTime = function () {
  1461. return this._currentFakeBaseSystemTime + this._currentTickTime;
  1462. };
  1463. Scheduler.prototype.setFakeBaseSystemTime = function (fakeBaseSystemTime) {
  1464. this._currentFakeBaseSystemTime = fakeBaseSystemTime;
  1465. };
  1466. Scheduler.prototype.getRealSystemTime = function () {
  1467. return OriginalDate.now();
  1468. };
  1469. Scheduler.prototype.scheduleFunction = function (cb, delay, options) {
  1470. options = __assign({
  1471. args: [],
  1472. isPeriodic: false,
  1473. isRequestAnimationFrame: false,
  1474. id: -1,
  1475. isRequeuePeriodic: false
  1476. }, options);
  1477. var currentId = options.id < 0 ? _a.nextId++ : options.id;
  1478. var endTime = this._currentTickTime + delay;
  1479. // Insert so that scheduler queue remains sorted by end time.
  1480. var newEntry = {
  1481. endTime: endTime,
  1482. id: currentId,
  1483. func: cb,
  1484. args: options.args,
  1485. delay: delay,
  1486. isPeriodic: options.isPeriodic,
  1487. isRequestAnimationFrame: options.isRequestAnimationFrame
  1488. };
  1489. if (options.isRequeuePeriodic) {
  1490. this._currentTickRequeuePeriodicEntries.push(newEntry);
  1491. }
  1492. var i = 0;
  1493. for (; i < this._schedulerQueue.length; i++) {
  1494. var currentEntry = this._schedulerQueue[i];
  1495. if (newEntry.endTime < currentEntry.endTime) {
  1496. break;
  1497. }
  1498. }
  1499. this._schedulerQueue.splice(i, 0, newEntry);
  1500. return currentId;
  1501. };
  1502. Scheduler.prototype.removeScheduledFunctionWithId = function (id) {
  1503. for (var i = 0; i < this._schedulerQueue.length; i++) {
  1504. if (this._schedulerQueue[i].id == id) {
  1505. this._schedulerQueue.splice(i, 1);
  1506. break;
  1507. }
  1508. }
  1509. };
  1510. Scheduler.prototype.removeAll = function () {
  1511. this._schedulerQueue = [];
  1512. };
  1513. Scheduler.prototype.getTimerCount = function () {
  1514. return this._schedulerQueue.length;
  1515. };
  1516. Scheduler.prototype.tickToNext = function (step, doTick, tickOptions) {
  1517. if (step === void 0) { step = 1; }
  1518. if (this._schedulerQueue.length < step) {
  1519. return;
  1520. }
  1521. // Find the last task currently queued in the scheduler queue and tick
  1522. // till that time.
  1523. var startTime = this._currentTickTime;
  1524. var targetTask = this._schedulerQueue[step - 1];
  1525. this.tick(targetTask.endTime - startTime, doTick, tickOptions);
  1526. };
  1527. Scheduler.prototype.tick = function (millis, doTick, tickOptions) {
  1528. if (millis === void 0) { millis = 0; }
  1529. var finalTime = this._currentTickTime + millis;
  1530. var lastCurrentTime = 0;
  1531. tickOptions = Object.assign({ processNewMacroTasksSynchronously: true }, tickOptions);
  1532. // we need to copy the schedulerQueue so nested timeout
  1533. // will not be wrongly called in the current tick
  1534. // https://github.com/angular/angular/issues/33799
  1535. var schedulerQueue = tickOptions.processNewMacroTasksSynchronously ?
  1536. this._schedulerQueue :
  1537. this._schedulerQueue.slice();
  1538. if (schedulerQueue.length === 0 && doTick) {
  1539. doTick(millis);
  1540. return;
  1541. }
  1542. while (schedulerQueue.length > 0) {
  1543. // clear requeueEntries before each loop
  1544. this._currentTickRequeuePeriodicEntries = [];
  1545. var current = schedulerQueue[0];
  1546. if (finalTime < current.endTime) {
  1547. // Done processing the queue since it's sorted by endTime.
  1548. break;
  1549. }
  1550. else {
  1551. // Time to run scheduled function. Remove it from the head of queue.
  1552. var current_1 = schedulerQueue.shift();
  1553. if (!tickOptions.processNewMacroTasksSynchronously) {
  1554. var idx = this._schedulerQueue.indexOf(current_1);
  1555. if (idx >= 0) {
  1556. this._schedulerQueue.splice(idx, 1);
  1557. }
  1558. }
  1559. lastCurrentTime = this._currentTickTime;
  1560. this._currentTickTime = current_1.endTime;
  1561. if (doTick) {
  1562. doTick(this._currentTickTime - lastCurrentTime);
  1563. }
  1564. var retval = current_1.func.apply(global, current_1.isRequestAnimationFrame ? [this._currentTickTime] : current_1.args);
  1565. if (!retval) {
  1566. // Uncaught exception in the current scheduled function. Stop processing the queue.
  1567. break;
  1568. }
  1569. // check is there any requeue periodic entry is added in
  1570. // current loop, if there is, we need to add to current loop
  1571. if (!tickOptions.processNewMacroTasksSynchronously) {
  1572. this._currentTickRequeuePeriodicEntries.forEach(function (newEntry) {
  1573. var i = 0;
  1574. for (; i < schedulerQueue.length; i++) {
  1575. var currentEntry = schedulerQueue[i];
  1576. if (newEntry.endTime < currentEntry.endTime) {
  1577. break;
  1578. }
  1579. }
  1580. schedulerQueue.splice(i, 0, newEntry);
  1581. });
  1582. }
  1583. }
  1584. }
  1585. lastCurrentTime = this._currentTickTime;
  1586. this._currentTickTime = finalTime;
  1587. if (doTick) {
  1588. doTick(this._currentTickTime - lastCurrentTime);
  1589. }
  1590. };
  1591. Scheduler.prototype.flushOnlyPendingTimers = function (doTick) {
  1592. if (this._schedulerQueue.length === 0) {
  1593. return 0;
  1594. }
  1595. // Find the last task currently queued in the scheduler queue and tick
  1596. // till that time.
  1597. var startTime = this._currentTickTime;
  1598. var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
  1599. this.tick(lastTask.endTime - startTime, doTick, { processNewMacroTasksSynchronously: false });
  1600. return this._currentTickTime - startTime;
  1601. };
  1602. Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
  1603. if (limit === void 0) { limit = 20; }
  1604. if (flushPeriodic === void 0) { flushPeriodic = false; }
  1605. if (flushPeriodic) {
  1606. return this.flushPeriodic(doTick);
  1607. }
  1608. else {
  1609. return this.flushNonPeriodic(limit, doTick);
  1610. }
  1611. };
  1612. Scheduler.prototype.flushPeriodic = function (doTick) {
  1613. if (this._schedulerQueue.length === 0) {
  1614. return 0;
  1615. }
  1616. // Find the last task currently queued in the scheduler queue and tick
  1617. // till that time.
  1618. var startTime = this._currentTickTime;
  1619. var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
  1620. this.tick(lastTask.endTime - startTime, doTick);
  1621. return this._currentTickTime - startTime;
  1622. };
  1623. Scheduler.prototype.flushNonPeriodic = function (limit, doTick) {
  1624. var startTime = this._currentTickTime;
  1625. var lastCurrentTime = 0;
  1626. var count = 0;
  1627. while (this._schedulerQueue.length > 0) {
  1628. count++;
  1629. if (count > limit) {
  1630. throw new Error('flush failed after reaching the limit of ' + limit +
  1631. ' tasks. Does your code use a polling timeout?');
  1632. }
  1633. // flush only non-periodic timers.
  1634. // If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
  1635. if (this._schedulerQueue.filter(function (task) { return !task.isPeriodic && !task.isRequestAnimationFrame; })
  1636. .length === 0) {
  1637. break;
  1638. }
  1639. var current = this._schedulerQueue.shift();
  1640. lastCurrentTime = this._currentTickTime;
  1641. this._currentTickTime = current.endTime;
  1642. if (doTick) {
  1643. // Update any secondary schedulers like Jasmine mock Date.
  1644. doTick(this._currentTickTime - lastCurrentTime);
  1645. }
  1646. var retval = current.func.apply(global, current.args);
  1647. if (!retval) {
  1648. // Uncaught exception in the current scheduled function. Stop processing the queue.
  1649. break;
  1650. }
  1651. }
  1652. return this._currentTickTime - startTime;
  1653. };
  1654. return Scheduler;
  1655. }());
  1656. _a = Scheduler;
  1657. // Next scheduler id.
  1658. (function () {
  1659. _a.nextId = 1;
  1660. })();
  1661. var FakeAsyncTestZoneSpec = /** @class */ (function () {
  1662. function FakeAsyncTestZoneSpec(namePrefix, trackPendingRequestAnimationFrame, macroTaskOptions) {
  1663. if (trackPendingRequestAnimationFrame === void 0) { trackPendingRequestAnimationFrame = false; }
  1664. this.trackPendingRequestAnimationFrame = trackPendingRequestAnimationFrame;
  1665. this.macroTaskOptions = macroTaskOptions;
  1666. this._scheduler = new Scheduler();
  1667. this._microtasks = [];
  1668. this._lastError = null;
  1669. this._uncaughtPromiseErrors = Promise[Zone.__symbol__('uncaughtPromiseErrors')];
  1670. this.pendingPeriodicTimers = [];
  1671. this.pendingTimers = [];
  1672. this.patchDateLocked = false;
  1673. this.properties = { 'FakeAsyncTestZoneSpec': this };
  1674. this.name = 'fakeAsyncTestZone for ' + namePrefix;
  1675. // in case user can't access the construction of FakeAsyncTestSpec
  1676. // user can also define macroTaskOptions by define a global variable.
  1677. if (!this.macroTaskOptions) {
  1678. this.macroTaskOptions = global[Zone.__symbol__('FakeAsyncTestMacroTask')];
  1679. }
  1680. }
  1681. FakeAsyncTestZoneSpec.assertInZone = function () {
  1682. if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
  1683. throw new Error('The code should be running in the fakeAsync zone to call this function');
  1684. }
  1685. };
  1686. FakeAsyncTestZoneSpec.prototype._fnAndFlush = function (fn, completers) {
  1687. var _this = this;
  1688. return function () {
  1689. var args = [];
  1690. for (var _i = 0; _i < arguments.length; _i++) {
  1691. args[_i] = arguments[_i];
  1692. }
  1693. fn.apply(global, args);
  1694. if (_this._lastError === null) { // Success
  1695. if (completers.onSuccess != null) {
  1696. completers.onSuccess.apply(global);
  1697. }
  1698. // Flush microtasks only on success.
  1699. _this.flushMicrotasks();
  1700. }
  1701. else { // Failure
  1702. if (completers.onError != null) {
  1703. completers.onError.apply(global);
  1704. }
  1705. }
  1706. // Return true if there were no errors, false otherwise.
  1707. return _this._lastError === null;
  1708. };
  1709. };
  1710. FakeAsyncTestZoneSpec._removeTimer = function (timers, id) {
  1711. var index = timers.indexOf(id);
  1712. if (index > -1) {
  1713. timers.splice(index, 1);
  1714. }
  1715. };
  1716. FakeAsyncTestZoneSpec.prototype._dequeueTimer = function (id) {
  1717. var _this = this;
  1718. return function () {
  1719. FakeAsyncTestZoneSpec._removeTimer(_this.pendingTimers, id);
  1720. };
  1721. };
  1722. FakeAsyncTestZoneSpec.prototype._requeuePeriodicTimer = function (fn, interval, args, id) {
  1723. var _this = this;
  1724. return function () {
  1725. // Requeue the timer callback if it's not been canceled.
  1726. if (_this.pendingPeriodicTimers.indexOf(id) !== -1) {
  1727. _this._scheduler.scheduleFunction(fn, interval, { args: args, isPeriodic: true, id: id, isRequeuePeriodic: true });
  1728. }
  1729. };
  1730. };
  1731. FakeAsyncTestZoneSpec.prototype._dequeuePeriodicTimer = function (id) {
  1732. var _this = this;
  1733. return function () {
  1734. FakeAsyncTestZoneSpec._removeTimer(_this.pendingPeriodicTimers, id);
  1735. };
  1736. };
  1737. FakeAsyncTestZoneSpec.prototype._setTimeout = function (fn, delay, args, isTimer) {
  1738. if (isTimer === void 0) { isTimer = true; }
  1739. var removeTimerFn = this._dequeueTimer(Scheduler.nextId);
  1740. // Queue the callback and dequeue the timer on success and error.
  1741. var cb = this._fnAndFlush(fn, { onSuccess: removeTimerFn, onError: removeTimerFn });
  1742. var id = this._scheduler.scheduleFunction(cb, delay, { args: args, isRequestAnimationFrame: !isTimer });
  1743. if (isTimer) {
  1744. this.pendingTimers.push(id);
  1745. }
  1746. return id;
  1747. };
  1748. FakeAsyncTestZoneSpec.prototype._clearTimeout = function (id) {
  1749. FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
  1750. this._scheduler.removeScheduledFunctionWithId(id);
  1751. };
  1752. FakeAsyncTestZoneSpec.prototype._setInterval = function (fn, interval, args) {
  1753. var id = Scheduler.nextId;
  1754. var completers = { onSuccess: null, onError: this._dequeuePeriodicTimer(id) };
  1755. var cb = this._fnAndFlush(fn, completers);
  1756. // Use the callback created above to requeue on success.
  1757. completers.onSuccess = this._requeuePeriodicTimer(cb, interval, args, id);
  1758. // Queue the callback and dequeue the periodic timer only on error.
  1759. this._scheduler.scheduleFunction(cb, interval, { args: args, isPeriodic: true });
  1760. this.pendingPeriodicTimers.push(id);
  1761. return id;
  1762. };
  1763. FakeAsyncTestZoneSpec.prototype._clearInterval = function (id) {
  1764. FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
  1765. this._scheduler.removeScheduledFunctionWithId(id);
  1766. };
  1767. FakeAsyncTestZoneSpec.prototype._resetLastErrorAndThrow = function () {
  1768. var error = this._lastError || this._uncaughtPromiseErrors[0];
  1769. this._uncaughtPromiseErrors.length = 0;
  1770. this._lastError = null;
  1771. throw error;
  1772. };
  1773. FakeAsyncTestZoneSpec.prototype.getCurrentTickTime = function () {
  1774. return this._scheduler.getCurrentTickTime();
  1775. };
  1776. FakeAsyncTestZoneSpec.prototype.getFakeSystemTime = function () {
  1777. return this._scheduler.getFakeSystemTime();
  1778. };
  1779. FakeAsyncTestZoneSpec.prototype.setFakeBaseSystemTime = function (realTime) {
  1780. this._scheduler.setFakeBaseSystemTime(realTime);
  1781. };
  1782. FakeAsyncTestZoneSpec.prototype.getRealSystemTime = function () {
  1783. return this._scheduler.getRealSystemTime();
  1784. };
  1785. FakeAsyncTestZoneSpec.patchDate = function () {
  1786. if (!!global[Zone.__symbol__('disableDatePatching')]) {
  1787. // we don't want to patch global Date
  1788. // because in some case, global Date
  1789. // is already being patched, we need to provide
  1790. // an option to let user still use their
  1791. // own version of Date.
  1792. return;
  1793. }
  1794. if (global['Date'] === FakeDate) {
  1795. // already patched
  1796. return;
  1797. }
  1798. global['Date'] = FakeDate;
  1799. FakeDate.prototype = OriginalDate.prototype;
  1800. // try check and reset timers
  1801. // because jasmine.clock().install() may
  1802. // have replaced the global timer
  1803. FakeAsyncTestZoneSpec.checkTimerPatch();
  1804. };
  1805. FakeAsyncTestZoneSpec.resetDate = function () {
  1806. if (global['Date'] === FakeDate) {
  1807. global['Date'] = OriginalDate;
  1808. }
  1809. };
  1810. FakeAsyncTestZoneSpec.checkTimerPatch = function () {
  1811. if (global.setTimeout !== timers.setTimeout) {
  1812. global.setTimeout = timers.setTimeout;
  1813. global.clearTimeout = timers.clearTimeout;
  1814. }
  1815. if (global.setInterval !== timers.setInterval) {
  1816. global.setInterval = timers.setInterval;
  1817. global.clearInterval = timers.clearInterval;
  1818. }
  1819. };
  1820. FakeAsyncTestZoneSpec.prototype.lockDatePatch = function () {
  1821. this.patchDateLocked = true;
  1822. FakeAsyncTestZoneSpec.patchDate();
  1823. };
  1824. FakeAsyncTestZoneSpec.prototype.unlockDatePatch = function () {
  1825. this.patchDateLocked = false;
  1826. FakeAsyncTestZoneSpec.resetDate();
  1827. };
  1828. FakeAsyncTestZoneSpec.prototype.tickToNext = function (steps, doTick, tickOptions) {
  1829. if (steps === void 0) { steps = 1; }
  1830. if (tickOptions === void 0) { tickOptions = { processNewMacroTasksSynchronously: true }; }
  1831. if (steps <= 0) {
  1832. return;
  1833. }
  1834. FakeAsyncTestZoneSpec.assertInZone();
  1835. this.flushMicrotasks();
  1836. this._scheduler.tickToNext(steps, doTick, tickOptions);
  1837. if (this._lastError !== null) {
  1838. this._resetLastErrorAndThrow();
  1839. }
  1840. };
  1841. FakeAsyncTestZoneSpec.prototype.tick = function (millis, doTick, tickOptions) {
  1842. if (millis === void 0) { millis = 0; }
  1843. if (tickOptions === void 0) { tickOptions = { processNewMacroTasksSynchronously: true }; }
  1844. FakeAsyncTestZoneSpec.assertInZone();
  1845. this.flushMicrotasks();
  1846. this._scheduler.tick(millis, doTick, tickOptions);
  1847. if (this._lastError !== null) {
  1848. this._resetLastErrorAndThrow();
  1849. }
  1850. };
  1851. FakeAsyncTestZoneSpec.prototype.flushMicrotasks = function () {
  1852. var _this = this;
  1853. FakeAsyncTestZoneSpec.assertInZone();
  1854. var flushErrors = function () {
  1855. if (_this._lastError !== null || _this._uncaughtPromiseErrors.length) {
  1856. // If there is an error stop processing the microtask queue and rethrow the error.
  1857. _this._resetLastErrorAndThrow();
  1858. }
  1859. };
  1860. while (this._microtasks.length > 0) {
  1861. var microtask = this._microtasks.shift();
  1862. microtask.func.apply(microtask.target, microtask.args);
  1863. }
  1864. flushErrors();
  1865. };
  1866. FakeAsyncTestZoneSpec.prototype.flush = function (limit, flushPeriodic, doTick) {
  1867. FakeAsyncTestZoneSpec.assertInZone();
  1868. this.flushMicrotasks();
  1869. var elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
  1870. if (this._lastError !== null) {
  1871. this._resetLastErrorAndThrow();
  1872. }
  1873. return elapsed;
  1874. };
  1875. FakeAsyncTestZoneSpec.prototype.flushOnlyPendingTimers = function (doTick) {
  1876. FakeAsyncTestZoneSpec.assertInZone();
  1877. this.flushMicrotasks();
  1878. var elapsed = this._scheduler.flushOnlyPendingTimers(doTick);
  1879. if (this._lastError !== null) {
  1880. this._resetLastErrorAndThrow();
  1881. }
  1882. return elapsed;
  1883. };
  1884. FakeAsyncTestZoneSpec.prototype.removeAllTimers = function () {
  1885. FakeAsyncTestZoneSpec.assertInZone();
  1886. this._scheduler.removeAll();
  1887. this.pendingPeriodicTimers = [];
  1888. this.pendingTimers = [];
  1889. };
  1890. FakeAsyncTestZoneSpec.prototype.getTimerCount = function () {
  1891. return this._scheduler.getTimerCount() + this._microtasks.length;
  1892. };
  1893. FakeAsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  1894. switch (task.type) {
  1895. case 'microTask':
  1896. var args = task.data && task.data.args;
  1897. // should pass additional arguments to callback if have any
  1898. // currently we know process.nextTick will have such additional
  1899. // arguments
  1900. var additionalArgs = void 0;
  1901. if (args) {
  1902. var callbackIndex = task.data.cbIdx;
  1903. if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
  1904. additionalArgs = Array.prototype.slice.call(args, callbackIndex + 1);
  1905. }
  1906. }
  1907. this._microtasks.push({
  1908. func: task.invoke,
  1909. args: additionalArgs,
  1910. target: task.data && task.data.target
  1911. });
  1912. break;
  1913. case 'macroTask':
  1914. switch (task.source) {
  1915. case 'setTimeout':
  1916. task.data['handleId'] = this._setTimeout(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  1917. break;
  1918. case 'setImmediate':
  1919. task.data['handleId'] = this._setTimeout(task.invoke, 0, Array.prototype.slice.call(task.data['args'], 1));
  1920. break;
  1921. case 'setInterval':
  1922. task.data['handleId'] = this._setInterval(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  1923. break;
  1924. case 'XMLHttpRequest.send':
  1925. throw new Error('Cannot make XHRs from within a fake async test. Request URL: ' +
  1926. task.data['url']);
  1927. case 'requestAnimationFrame':
  1928. case 'webkitRequestAnimationFrame':
  1929. case 'mozRequestAnimationFrame':
  1930. // Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
  1931. // (60 frames per second)
  1932. task.data['handleId'] = this._setTimeout(task.invoke, 16, task.data['args'], this.trackPendingRequestAnimationFrame);
  1933. break;
  1934. default:
  1935. // user can define which macroTask they want to support by passing
  1936. // macroTaskOptions
  1937. var macroTaskOption = this.findMacroTaskOption(task);
  1938. if (macroTaskOption) {
  1939. var args_1 = task.data && task.data['args'];
  1940. var delay = args_1 && args_1.length > 1 ? args_1[1] : 0;
  1941. var callbackArgs = macroTaskOption.callbackArgs ? macroTaskOption.callbackArgs : args_1;
  1942. if (!!macroTaskOption.isPeriodic) {
  1943. // periodic macroTask, use setInterval to simulate
  1944. task.data['handleId'] = this._setInterval(task.invoke, delay, callbackArgs);
  1945. task.data.isPeriodic = true;
  1946. }
  1947. else {
  1948. // not periodic, use setTimeout to simulate
  1949. task.data['handleId'] = this._setTimeout(task.invoke, delay, callbackArgs);
  1950. }
  1951. break;
  1952. }
  1953. throw new Error('Unknown macroTask scheduled in fake async test: ' + task.source);
  1954. }
  1955. break;
  1956. case 'eventTask':
  1957. task = delegate.scheduleTask(target, task);
  1958. break;
  1959. }
  1960. return task;
  1961. };
  1962. FakeAsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  1963. switch (task.source) {
  1964. case 'setTimeout':
  1965. case 'requestAnimationFrame':
  1966. case 'webkitRequestAnimationFrame':
  1967. case 'mozRequestAnimationFrame':
  1968. return this._clearTimeout(task.data['handleId']);
  1969. case 'setInterval':
  1970. return this._clearInterval(task.data['handleId']);
  1971. default:
  1972. // user can define which macroTask they want to support by passing
  1973. // macroTaskOptions
  1974. var macroTaskOption = this.findMacroTaskOption(task);
  1975. if (macroTaskOption) {
  1976. var handleId = task.data['handleId'];
  1977. return macroTaskOption.isPeriodic ? this._clearInterval(handleId) :
  1978. this._clearTimeout(handleId);
  1979. }
  1980. return delegate.cancelTask(target, task);
  1981. }
  1982. };
  1983. FakeAsyncTestZoneSpec.prototype.onInvoke = function (delegate, current, target, callback, applyThis, applyArgs, source) {
  1984. try {
  1985. FakeAsyncTestZoneSpec.patchDate();
  1986. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  1987. }
  1988. finally {
  1989. if (!this.patchDateLocked) {
  1990. FakeAsyncTestZoneSpec.resetDate();
  1991. }
  1992. }
  1993. };
  1994. FakeAsyncTestZoneSpec.prototype.findMacroTaskOption = function (task) {
  1995. if (!this.macroTaskOptions) {
  1996. return null;
  1997. }
  1998. for (var i = 0; i < this.macroTaskOptions.length; i++) {
  1999. var macroTaskOption = this.macroTaskOptions[i];
  2000. if (macroTaskOption.source === task.source) {
  2001. return macroTaskOption;
  2002. }
  2003. }
  2004. return null;
  2005. };
  2006. FakeAsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  2007. this._lastError = error;
  2008. return false; // Don't propagate error to parent zone.
  2009. };
  2010. return FakeAsyncTestZoneSpec;
  2011. }());
  2012. // Export the class so that new instances can be created with proper
  2013. // constructor params.
  2014. Zone['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
  2015. })(typeof window === 'object' && window || typeof self === 'object' && self || global);
  2016. Zone.__load_patch('fakeasync', function (global, Zone, api) {
  2017. var FakeAsyncTestZoneSpec = Zone && Zone['FakeAsyncTestZoneSpec'];
  2018. function getProxyZoneSpec() {
  2019. return Zone && Zone['ProxyZoneSpec'];
  2020. }
  2021. var _fakeAsyncTestZoneSpec = null;
  2022. /**
  2023. * Clears out the shared fake async zone for a test.
  2024. * To be called in a global `beforeEach`.
  2025. *
  2026. * @experimental
  2027. */
  2028. function resetFakeAsyncZone() {
  2029. if (_fakeAsyncTestZoneSpec) {
  2030. _fakeAsyncTestZoneSpec.unlockDatePatch();
  2031. }
  2032. _fakeAsyncTestZoneSpec = null;
  2033. // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
  2034. getProxyZoneSpec() && getProxyZoneSpec().assertPresent().resetDelegate();
  2035. }
  2036. /**
  2037. * Wraps a function to be executed in the fakeAsync zone:
  2038. * - microtasks are manually executed by calling `flushMicrotasks()`,
  2039. * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
  2040. *
  2041. * If there are any pending timers at the end of the function, an exception will be thrown.
  2042. *
  2043. * Can be used to wrap inject() calls.
  2044. *
  2045. * ## Example
  2046. *
  2047. * {@example core/testing/ts/fake_async.ts region='basic'}
  2048. *
  2049. * @param fn
  2050. * @returns The function wrapped to be executed in the fakeAsync zone
  2051. *
  2052. * @experimental
  2053. */
  2054. function fakeAsync(fn) {
  2055. // Not using an arrow function to preserve context passed from call site
  2056. var fakeAsyncFn = function () {
  2057. var args = [];
  2058. for (var _i = 0; _i < arguments.length; _i++) {
  2059. args[_i] = arguments[_i];
  2060. }
  2061. var ProxyZoneSpec = getProxyZoneSpec();
  2062. if (!ProxyZoneSpec) {
  2063. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  2064. 'Please make sure that your environment includes zone.js/plugins/proxy');
  2065. }
  2066. var proxyZoneSpec = ProxyZoneSpec.assertPresent();
  2067. if (Zone.current.get('FakeAsyncTestZoneSpec')) {
  2068. throw new Error('fakeAsync() calls can not be nested');
  2069. }
  2070. try {
  2071. // in case jasmine.clock init a fakeAsyncTestZoneSpec
  2072. if (!_fakeAsyncTestZoneSpec) {
  2073. if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
  2074. throw new Error('fakeAsync() calls can not be nested');
  2075. }
  2076. _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
  2077. }
  2078. var res = void 0;
  2079. var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
  2080. proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
  2081. _fakeAsyncTestZoneSpec.lockDatePatch();
  2082. try {
  2083. res = fn.apply(this, args);
  2084. flushMicrotasks();
  2085. }
  2086. finally {
  2087. proxyZoneSpec.setDelegate(lastProxyZoneSpec);
  2088. }
  2089. if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
  2090. throw new Error("".concat(_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length, " ") +
  2091. "periodic timer(s) still in the queue.");
  2092. }
  2093. if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
  2094. throw new Error("".concat(_fakeAsyncTestZoneSpec.pendingTimers.length, " timer(s) still in the queue."));
  2095. }
  2096. return res;
  2097. }
  2098. finally {
  2099. resetFakeAsyncZone();
  2100. }
  2101. };
  2102. fakeAsyncFn.isFakeAsync = true;
  2103. return fakeAsyncFn;
  2104. }
  2105. function _getFakeAsyncZoneSpec() {
  2106. if (_fakeAsyncTestZoneSpec == null) {
  2107. _fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2108. if (_fakeAsyncTestZoneSpec == null) {
  2109. throw new Error('The code should be running in the fakeAsync zone to call this function');
  2110. }
  2111. }
  2112. return _fakeAsyncTestZoneSpec;
  2113. }
  2114. /**
  2115. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
  2116. *
  2117. * The microtasks queue is drained at the very start of this function and after any timer callback
  2118. * has been executed.
  2119. *
  2120. * ## Example
  2121. *
  2122. * {@example core/testing/ts/fake_async.ts region='basic'}
  2123. *
  2124. * @experimental
  2125. */
  2126. function tick(millis, ignoreNestedTimeout) {
  2127. if (millis === void 0) { millis = 0; }
  2128. if (ignoreNestedTimeout === void 0) { ignoreNestedTimeout = false; }
  2129. _getFakeAsyncZoneSpec().tick(millis, null, ignoreNestedTimeout);
  2130. }
  2131. /**
  2132. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
  2133. * draining the macrotask queue until it is empty. The returned value is the milliseconds
  2134. * of time that would have been elapsed.
  2135. *
  2136. * @param maxTurns
  2137. * @returns The simulated time elapsed, in millis.
  2138. *
  2139. * @experimental
  2140. */
  2141. function flush(maxTurns) {
  2142. return _getFakeAsyncZoneSpec().flush(maxTurns);
  2143. }
  2144. /**
  2145. * Discard all remaining periodic tasks.
  2146. *
  2147. * @experimental
  2148. */
  2149. function discardPeriodicTasks() {
  2150. var zoneSpec = _getFakeAsyncZoneSpec();
  2151. zoneSpec.pendingPeriodicTimers;
  2152. zoneSpec.pendingPeriodicTimers.length = 0;
  2153. }
  2154. /**
  2155. * Flush any pending microtasks.
  2156. *
  2157. * @experimental
  2158. */
  2159. function flushMicrotasks() {
  2160. _getFakeAsyncZoneSpec().flushMicrotasks();
  2161. }
  2162. Zone[api.symbol('fakeAsyncTest')] =
  2163. { resetFakeAsyncZone: resetFakeAsyncZone, flushMicrotasks: flushMicrotasks, discardPeriodicTasks: discardPeriodicTasks, tick: tick, flush: flush, fakeAsync: fakeAsync };
  2164. }, true);
  2165. /**
  2166. * Promise for async/fakeAsync zoneSpec test
  2167. * can support async operation which not supported by zone.js
  2168. * such as
  2169. * it ('test jsonp in AsyncZone', async() => {
  2170. * new Promise(res => {
  2171. * jsonp(url, (data) => {
  2172. * // success callback
  2173. * res(data);
  2174. * });
  2175. * }).then((jsonpResult) => {
  2176. * // get jsonp result.
  2177. *
  2178. * // user will expect AsyncZoneSpec wait for
  2179. * // then, but because jsonp is not zone aware
  2180. * // AsyncZone will finish before then is called.
  2181. * });
  2182. * });
  2183. */
  2184. Zone.__load_patch('promisefortest', function (global, Zone, api) {
  2185. var symbolState = api.symbol('state');
  2186. var UNRESOLVED = null;
  2187. var symbolParentUnresolved = api.symbol('parentUnresolved');
  2188. // patch Promise.prototype.then to keep an internal
  2189. // number for tracking unresolved chained promise
  2190. // we will decrease this number when the parent promise
  2191. // being resolved/rejected and chained promise was
  2192. // scheduled as a microTask.
  2193. // so we can know such kind of chained promise still
  2194. // not resolved in AsyncTestZone
  2195. Promise[api.symbol('patchPromiseForTest')] = function patchPromiseForTest() {
  2196. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  2197. if (oriThen) {
  2198. return;
  2199. }
  2200. oriThen = Promise[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
  2201. Promise.prototype.then = function () {
  2202. var chained = oriThen.apply(this, arguments);
  2203. if (this[symbolState] === UNRESOLVED) {
  2204. // parent promise is unresolved.
  2205. var asyncTestZoneSpec = Zone.current.get('AsyncTestZoneSpec');
  2206. if (asyncTestZoneSpec) {
  2207. asyncTestZoneSpec.unresolvedChainedPromiseCount++;
  2208. chained[symbolParentUnresolved] = true;
  2209. }
  2210. }
  2211. return chained;
  2212. };
  2213. };
  2214. Promise[api.symbol('unPatchPromiseForTest')] = function unpatchPromiseForTest() {
  2215. // restore origin then
  2216. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  2217. if (oriThen) {
  2218. Promise.prototype.then = oriThen;
  2219. Promise[Zone.__symbol__('ZonePromiseThen')] = undefined;
  2220. }
  2221. };
  2222. });
  2223. }));