zone-testing.umd.js 112 KB

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