zone-testing.js 97 KB

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