zone-testing.umd.js 114 KB

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