zone-testing.js 95 KB

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