testing.js 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661
  1. /**
  2. * @license Angular v8.1.0
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import { getDebugNode, RendererFactory2, InjectionToken, ɵstringify, ɵReflectionCapabilities, Directive, Component, Pipe, NgModule, ɵgetInjectableDef, ɵNG_COMPONENT_DEF, ɵRender3NgModuleRef, LOCALE_ID, ɵDEFAULT_LOCALE_ID, ɵsetLocaleId, ApplicationInitStatus, ɵRender3ComponentFactory, ɵcompileComponent, ɵNG_DIRECTIVE_DEF, ɵcompileDirective, ɵNG_PIPE_DEF, ɵcompilePipe, ɵpatchComponentDefWithScope, ɵNG_INJECTOR_DEF, ɵNG_MODULE_DEF, ɵcompileNgModuleDefs, NgZone, Compiler, COMPILER_OPTIONS, ɵNgModuleFactory, ModuleWithComponentFactories, ɵtransitiveScopesFor, Injector, InjectFlags, ɵresetCompiledComponents, ɵflushModuleScopingQueueAsMuchAsPossible, Injectable, ɵclearOverrides, ɵoverrideComponentView, ɵAPP_ROOT, ɵoverrideProvider, ɵivyEnabled, Optional, SkipSelf } from '@angular/core';
  7. import { __awaiter } from 'tslib';
  8. import { ResourceLoader } from '@angular/compiler';
  9. /**
  10. * @fileoverview added by tsickle
  11. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  12. */
  13. /**
  14. * @license
  15. * Copyright Google Inc. All Rights Reserved.
  16. *
  17. * Use of this source code is governed by an MIT-style license that can be
  18. * found in the LICENSE file at https://angular.io/license
  19. */
  20. /** @type {?} */
  21. const _global = (/** @type {?} */ ((typeof window === 'undefined' ? global : window)));
  22. /**
  23. * Wraps a test function in an asynchronous test zone. The test will automatically
  24. * complete when all asynchronous calls within this zone are done. Can be used
  25. * to wrap an {\@link inject} call.
  26. *
  27. * Example:
  28. *
  29. * ```
  30. * it('...', async(inject([AClass], (object) => {
  31. * object.doSomething.then(() => {
  32. * expect(...);
  33. * })
  34. * });
  35. * ```
  36. *
  37. *
  38. * @param {?} fn
  39. * @return {?}
  40. */
  41. function asyncFallback(fn) {
  42. // If we're running using the Jasmine test framework, adapt to call the 'done'
  43. // function when asynchronous activity is finished.
  44. if (_global.jasmine) {
  45. // Not using an arrow function to preserve context passed from call site
  46. return (/**
  47. * @param {?} done
  48. * @return {?}
  49. */
  50. function (done) {
  51. if (!done) {
  52. // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
  53. // fake it here and assume sync.
  54. done = (/**
  55. * @return {?}
  56. */
  57. function () { });
  58. done.fail = (/**
  59. * @param {?} e
  60. * @return {?}
  61. */
  62. function (e) { throw e; });
  63. }
  64. runInTestZone(fn, this, done, (/**
  65. * @param {?} err
  66. * @return {?}
  67. */
  68. (err) => {
  69. if (typeof err === 'string') {
  70. return done.fail(new Error((/** @type {?} */ (err))));
  71. }
  72. else {
  73. done.fail(err);
  74. }
  75. }));
  76. });
  77. }
  78. // Otherwise, return a promise which will resolve when asynchronous activity
  79. // is finished. This will be correctly consumed by the Mocha framework with
  80. // it('...', async(myFn)); or can be used in a custom framework.
  81. // Not using an arrow function to preserve context passed from call site
  82. return (/**
  83. * @return {?}
  84. */
  85. function () {
  86. return new Promise((/**
  87. * @param {?} finishCallback
  88. * @param {?} failCallback
  89. * @return {?}
  90. */
  91. (finishCallback, failCallback) => {
  92. runInTestZone(fn, this, finishCallback, failCallback);
  93. }));
  94. });
  95. }
  96. /**
  97. * @param {?} fn
  98. * @param {?} context
  99. * @param {?} finishCallback
  100. * @param {?} failCallback
  101. * @return {?}
  102. */
  103. function runInTestZone(fn, context, finishCallback, failCallback) {
  104. /** @type {?} */
  105. const currentZone = Zone.current;
  106. /** @type {?} */
  107. const AsyncTestZoneSpec = ((/** @type {?} */ (Zone)))['AsyncTestZoneSpec'];
  108. if (AsyncTestZoneSpec === undefined) {
  109. throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
  110. 'Please make sure that your environment includes zone.js/dist/async-test.js');
  111. }
  112. /** @type {?} */
  113. const ProxyZoneSpec = (/** @type {?} */ (((/** @type {?} */ (Zone)))['ProxyZoneSpec']));
  114. if (ProxyZoneSpec === undefined) {
  115. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  116. 'Please make sure that your environment includes zone.js/dist/proxy.js');
  117. }
  118. /** @type {?} */
  119. const proxyZoneSpec = ProxyZoneSpec.get();
  120. ProxyZoneSpec.assertPresent();
  121. // We need to create the AsyncTestZoneSpec outside the ProxyZone.
  122. // If we do it in ProxyZone then we will get to infinite recursion.
  123. /** @type {?} */
  124. const proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
  125. /** @type {?} */
  126. const previousDelegate = proxyZoneSpec.getDelegate();
  127. (/** @type {?} */ ((/** @type {?} */ (proxyZone)).parent)).run((/**
  128. * @return {?}
  129. */
  130. () => {
  131. /** @type {?} */
  132. const testZoneSpec = new AsyncTestZoneSpec((/**
  133. * @return {?}
  134. */
  135. () => {
  136. // Need to restore the original zone.
  137. currentZone.run((/**
  138. * @return {?}
  139. */
  140. () => {
  141. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  142. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  143. proxyZoneSpec.setDelegate(previousDelegate);
  144. }
  145. finishCallback();
  146. }));
  147. }), (/**
  148. * @param {?} error
  149. * @return {?}
  150. */
  151. (error) => {
  152. // Need to restore the original zone.
  153. currentZone.run((/**
  154. * @return {?}
  155. */
  156. () => {
  157. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  158. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  159. proxyZoneSpec.setDelegate(previousDelegate);
  160. }
  161. failCallback(error);
  162. }));
  163. }), 'test');
  164. proxyZoneSpec.setDelegate(testZoneSpec);
  165. }));
  166. return Zone.current.runGuarded(fn, context);
  167. }
  168. /**
  169. * @fileoverview added by tsickle
  170. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  171. */
  172. /**
  173. * Wraps a test function in an asynchronous test zone. The test will automatically
  174. * complete when all asynchronous calls within this zone are done. Can be used
  175. * to wrap an {\@link inject} call.
  176. *
  177. * Example:
  178. *
  179. * ```
  180. * it('...', async(inject([AClass], (object) => {
  181. * object.doSomething.then(() => {
  182. * expect(...);
  183. * })
  184. * });
  185. * ```
  186. *
  187. * \@publicApi
  188. * @param {?} fn
  189. * @return {?}
  190. */
  191. function async(fn) {
  192. /** @type {?} */
  193. const _Zone = typeof Zone !== 'undefined' ? Zone : null;
  194. if (!_Zone) {
  195. return (/**
  196. * @return {?}
  197. */
  198. function () {
  199. return Promise.reject('Zone is needed for the async() test helper but could not be found. ' +
  200. 'Please make sure that your environment includes zone.js/dist/zone.js');
  201. });
  202. }
  203. /** @type {?} */
  204. const asyncTest = _Zone && _Zone[_Zone.__symbol__('asyncTest')];
  205. if (typeof asyncTest === 'function') {
  206. return asyncTest(fn);
  207. }
  208. // not using new version of zone.js
  209. // TODO @JiaLiPassion, remove this after all library updated to
  210. // newest version of zone.js(0.8.25)
  211. return asyncFallback(fn);
  212. }
  213. /**
  214. * @fileoverview added by tsickle
  215. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  216. */
  217. /**
  218. * Fixture for debugging and testing a component.
  219. *
  220. * \@publicApi
  221. * @template T
  222. */
  223. class ComponentFixture {
  224. /**
  225. * @param {?} componentRef
  226. * @param {?} ngZone
  227. * @param {?} _autoDetect
  228. */
  229. constructor(componentRef, ngZone, _autoDetect) {
  230. this.componentRef = componentRef;
  231. this.ngZone = ngZone;
  232. this._autoDetect = _autoDetect;
  233. this._isStable = true;
  234. this._isDestroyed = false;
  235. this._resolve = null;
  236. this._promise = null;
  237. this._onUnstableSubscription = null;
  238. this._onStableSubscription = null;
  239. this._onMicrotaskEmptySubscription = null;
  240. this._onErrorSubscription = null;
  241. this.changeDetectorRef = componentRef.changeDetectorRef;
  242. this.elementRef = componentRef.location;
  243. this.debugElement = (/** @type {?} */ (getDebugNode(this.elementRef.nativeElement)));
  244. this.componentInstance = componentRef.instance;
  245. this.nativeElement = this.elementRef.nativeElement;
  246. this.componentRef = componentRef;
  247. this.ngZone = ngZone;
  248. if (ngZone) {
  249. // Create subscriptions outside the NgZone so that the callbacks run oustide
  250. // of NgZone.
  251. ngZone.runOutsideAngular((/**
  252. * @return {?}
  253. */
  254. () => {
  255. this._onUnstableSubscription =
  256. ngZone.onUnstable.subscribe({ next: (/**
  257. * @return {?}
  258. */
  259. () => { this._isStable = false; }) });
  260. this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
  261. next: (/**
  262. * @return {?}
  263. */
  264. () => {
  265. if (this._autoDetect) {
  266. // Do a change detection run with checkNoChanges set to true to check
  267. // there are no changes on the second run.
  268. this.detectChanges(true);
  269. }
  270. })
  271. });
  272. this._onStableSubscription = ngZone.onStable.subscribe({
  273. next: (/**
  274. * @return {?}
  275. */
  276. () => {
  277. this._isStable = true;
  278. // Check whether there is a pending whenStable() completer to resolve.
  279. if (this._promise !== null) {
  280. // If so check whether there are no pending macrotasks before resolving.
  281. // Do this check in the next tick so that ngZone gets a chance to update the state of
  282. // pending macrotasks.
  283. scheduleMicroTask((/**
  284. * @return {?}
  285. */
  286. () => {
  287. if (!ngZone.hasPendingMacrotasks) {
  288. if (this._promise !== null) {
  289. (/** @type {?} */ (this._resolve))(true);
  290. this._resolve = null;
  291. this._promise = null;
  292. }
  293. }
  294. }));
  295. }
  296. })
  297. });
  298. this._onErrorSubscription =
  299. ngZone.onError.subscribe({ next: (/**
  300. * @param {?} error
  301. * @return {?}
  302. */
  303. (error) => { throw error; }) });
  304. }));
  305. }
  306. }
  307. /**
  308. * @private
  309. * @param {?} checkNoChanges
  310. * @return {?}
  311. */
  312. _tick(checkNoChanges) {
  313. this.changeDetectorRef.detectChanges();
  314. if (checkNoChanges) {
  315. this.checkNoChanges();
  316. }
  317. }
  318. /**
  319. * Trigger a change detection cycle for the component.
  320. * @param {?=} checkNoChanges
  321. * @return {?}
  322. */
  323. detectChanges(checkNoChanges = true) {
  324. if (this.ngZone != null) {
  325. // Run the change detection inside the NgZone so that any async tasks as part of the change
  326. // detection are captured by the zone and can be waited for in isStable.
  327. this.ngZone.run((/**
  328. * @return {?}
  329. */
  330. () => { this._tick(checkNoChanges); }));
  331. }
  332. else {
  333. // Running without zone. Just do the change detection.
  334. this._tick(checkNoChanges);
  335. }
  336. }
  337. /**
  338. * Do a change detection run to make sure there were no changes.
  339. * @return {?}
  340. */
  341. checkNoChanges() { this.changeDetectorRef.checkNoChanges(); }
  342. /**
  343. * Set whether the fixture should autodetect changes.
  344. *
  345. * Also runs detectChanges once so that any existing change is detected.
  346. * @param {?=} autoDetect
  347. * @return {?}
  348. */
  349. autoDetectChanges(autoDetect = true) {
  350. if (this.ngZone == null) {
  351. throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set');
  352. }
  353. this._autoDetect = autoDetect;
  354. this.detectChanges();
  355. }
  356. /**
  357. * Return whether the fixture is currently stable or has async tasks that have not been completed
  358. * yet.
  359. * @return {?}
  360. */
  361. isStable() { return this._isStable && !(/** @type {?} */ (this.ngZone)).hasPendingMacrotasks; }
  362. /**
  363. * Get a promise that resolves when the fixture is stable.
  364. *
  365. * This can be used to resume testing after events have triggered asynchronous activity or
  366. * asynchronous change detection.
  367. * @return {?}
  368. */
  369. whenStable() {
  370. if (this.isStable()) {
  371. return Promise.resolve(false);
  372. }
  373. else if (this._promise !== null) {
  374. return this._promise;
  375. }
  376. else {
  377. this._promise = new Promise((/**
  378. * @param {?} res
  379. * @return {?}
  380. */
  381. res => { this._resolve = res; }));
  382. return this._promise;
  383. }
  384. }
  385. /**
  386. * @private
  387. * @return {?}
  388. */
  389. _getRenderer() {
  390. if (this._renderer === undefined) {
  391. this._renderer = this.componentRef.injector.get(RendererFactory2, null);
  392. }
  393. return (/** @type {?} */ (this._renderer));
  394. }
  395. /**
  396. * Get a promise that resolves when the ui state is stable following animations.
  397. * @return {?}
  398. */
  399. whenRenderingDone() {
  400. /** @type {?} */
  401. const renderer = this._getRenderer();
  402. if (renderer && renderer.whenRenderingDone) {
  403. return renderer.whenRenderingDone();
  404. }
  405. return this.whenStable();
  406. }
  407. /**
  408. * Trigger component destruction.
  409. * @return {?}
  410. */
  411. destroy() {
  412. if (!this._isDestroyed) {
  413. this.componentRef.destroy();
  414. if (this._onUnstableSubscription != null) {
  415. this._onUnstableSubscription.unsubscribe();
  416. this._onUnstableSubscription = null;
  417. }
  418. if (this._onStableSubscription != null) {
  419. this._onStableSubscription.unsubscribe();
  420. this._onStableSubscription = null;
  421. }
  422. if (this._onMicrotaskEmptySubscription != null) {
  423. this._onMicrotaskEmptySubscription.unsubscribe();
  424. this._onMicrotaskEmptySubscription = null;
  425. }
  426. if (this._onErrorSubscription != null) {
  427. this._onErrorSubscription.unsubscribe();
  428. this._onErrorSubscription = null;
  429. }
  430. this._isDestroyed = true;
  431. }
  432. }
  433. }
  434. /**
  435. * @param {?} fn
  436. * @return {?}
  437. */
  438. function scheduleMicroTask(fn) {
  439. Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
  440. }
  441. /**
  442. * @fileoverview added by tsickle
  443. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  444. */
  445. /**
  446. * @license
  447. * Copyright Google Inc. All Rights Reserved.
  448. *
  449. * Use of this source code is governed by an MIT-style license that can be
  450. * found in the LICENSE file at https://angular.io/license
  451. */
  452. /**
  453. * fakeAsync has been moved to zone.js
  454. * this file is for fallback in case old version of zone.js is used
  455. * @type {?}
  456. */
  457. const _Zone = typeof Zone !== 'undefined' ? Zone : null;
  458. /** @type {?} */
  459. const FakeAsyncTestZoneSpec = _Zone && _Zone['FakeAsyncTestZoneSpec'];
  460. /** @type {?} */
  461. const ProxyZoneSpec = _Zone && _Zone['ProxyZoneSpec'];
  462. /** @type {?} */
  463. let _fakeAsyncTestZoneSpec = null;
  464. /**
  465. * Clears out the shared fake async zone for a test.
  466. * To be called in a global `beforeEach`.
  467. *
  468. * \@publicApi
  469. * @return {?}
  470. */
  471. function resetFakeAsyncZoneFallback() {
  472. _fakeAsyncTestZoneSpec = null;
  473. // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
  474. ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
  475. }
  476. /** @type {?} */
  477. let _inFakeAsyncCall = false;
  478. /**
  479. * Wraps a function to be executed in the fakeAsync zone:
  480. * - microtasks are manually executed by calling `flushMicrotasks()`,
  481. * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
  482. *
  483. * If there are any pending timers at the end of the function, an exception will be thrown.
  484. *
  485. * Can be used to wrap inject() calls.
  486. *
  487. * \@usageNotes
  488. * ### Example
  489. *
  490. * {\@example core/testing/ts/fake_async.ts region='basic'}
  491. *
  492. * \@publicApi
  493. * @param {?} fn
  494. * @return {?} The function wrapped to be executed in the fakeAsync zone
  495. *
  496. */
  497. function fakeAsyncFallback(fn) {
  498. // Not using an arrow function to preserve context passed from call site
  499. return (/**
  500. * @param {...?} args
  501. * @return {?}
  502. */
  503. function (...args) {
  504. /** @type {?} */
  505. const proxyZoneSpec = ProxyZoneSpec.assertPresent();
  506. if (_inFakeAsyncCall) {
  507. throw new Error('fakeAsync() calls can not be nested');
  508. }
  509. _inFakeAsyncCall = true;
  510. try {
  511. if (!_fakeAsyncTestZoneSpec) {
  512. if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
  513. throw new Error('fakeAsync() calls can not be nested');
  514. }
  515. _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
  516. }
  517. /** @type {?} */
  518. let res;
  519. /** @type {?} */
  520. const lastProxyZoneSpec = proxyZoneSpec.getDelegate();
  521. proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
  522. try {
  523. res = fn.apply(this, args);
  524. flushMicrotasksFallback();
  525. }
  526. finally {
  527. proxyZoneSpec.setDelegate(lastProxyZoneSpec);
  528. }
  529. if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
  530. throw new Error(`${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` +
  531. `periodic timer(s) still in the queue.`);
  532. }
  533. if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
  534. throw new Error(`${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`);
  535. }
  536. return res;
  537. }
  538. finally {
  539. _inFakeAsyncCall = false;
  540. resetFakeAsyncZoneFallback();
  541. }
  542. });
  543. }
  544. /**
  545. * @return {?}
  546. */
  547. function _getFakeAsyncZoneSpec() {
  548. if (_fakeAsyncTestZoneSpec == null) {
  549. throw new Error('The code should be running in the fakeAsync zone to call this function');
  550. }
  551. return _fakeAsyncTestZoneSpec;
  552. }
  553. /**
  554. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
  555. *
  556. * The microtasks queue is drained at the very start of this function and after any timer callback
  557. * has been executed.
  558. *
  559. * \@usageNotes
  560. * ### Example
  561. *
  562. * {\@example core/testing/ts/fake_async.ts region='basic'}
  563. *
  564. * \@publicApi
  565. * @param {?=} millis
  566. * @return {?}
  567. */
  568. function tickFallback(millis = 0) {
  569. _getFakeAsyncZoneSpec().tick(millis);
  570. }
  571. /**
  572. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
  573. * draining the macrotask queue until it is empty. The returned value is the milliseconds
  574. * of time that would have been elapsed.
  575. *
  576. * \@publicApi
  577. * @param {?=} maxTurns
  578. * @return {?} The simulated time elapsed, in millis.
  579. *
  580. */
  581. function flushFallback(maxTurns) {
  582. return _getFakeAsyncZoneSpec().flush(maxTurns);
  583. }
  584. /**
  585. * Discard all remaining periodic tasks.
  586. *
  587. * \@publicApi
  588. * @return {?}
  589. */
  590. function discardPeriodicTasksFallback() {
  591. /** @type {?} */
  592. const zoneSpec = _getFakeAsyncZoneSpec();
  593. zoneSpec.pendingPeriodicTimers.length = 0;
  594. }
  595. /**
  596. * Flush any pending microtasks.
  597. *
  598. * \@publicApi
  599. * @return {?}
  600. */
  601. function flushMicrotasksFallback() {
  602. _getFakeAsyncZoneSpec().flushMicrotasks();
  603. }
  604. /**
  605. * @fileoverview added by tsickle
  606. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  607. */
  608. /** @type {?} */
  609. const _Zone$1 = typeof Zone !== 'undefined' ? Zone : null;
  610. /** @type {?} */
  611. const fakeAsyncTestModule = _Zone$1 && _Zone$1[_Zone$1.__symbol__('fakeAsyncTest')];
  612. /**
  613. * Clears out the shared fake async zone for a test.
  614. * To be called in a global `beforeEach`.
  615. *
  616. * \@publicApi
  617. * @return {?}
  618. */
  619. function resetFakeAsyncZone() {
  620. if (fakeAsyncTestModule) {
  621. return fakeAsyncTestModule.resetFakeAsyncZone();
  622. }
  623. else {
  624. return resetFakeAsyncZoneFallback();
  625. }
  626. }
  627. /**
  628. * Wraps a function to be executed in the fakeAsync zone:
  629. * - microtasks are manually executed by calling `flushMicrotasks()`,
  630. * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
  631. *
  632. * If there are any pending timers at the end of the function, an exception will be thrown.
  633. *
  634. * Can be used to wrap inject() calls.
  635. *
  636. * \@usageNotes
  637. * ### Example
  638. *
  639. * {\@example core/testing/ts/fake_async.ts region='basic'}
  640. *
  641. * \@publicApi
  642. * @param {?} fn
  643. * @return {?} The function wrapped to be executed in the fakeAsync zone
  644. *
  645. */
  646. function fakeAsync(fn) {
  647. if (fakeAsyncTestModule) {
  648. return fakeAsyncTestModule.fakeAsync(fn);
  649. }
  650. else {
  651. return fakeAsyncFallback(fn);
  652. }
  653. }
  654. /**
  655. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
  656. *
  657. * The microtasks queue is drained at the very start of this function and after any timer callback
  658. * has been executed.
  659. *
  660. * \@usageNotes
  661. * ### Example
  662. *
  663. * {\@example core/testing/ts/fake_async.ts region='basic'}
  664. *
  665. * \@publicApi
  666. * @param {?=} millis
  667. * @return {?}
  668. */
  669. function tick(millis = 0) {
  670. if (fakeAsyncTestModule) {
  671. return fakeAsyncTestModule.tick(millis);
  672. }
  673. else {
  674. return tickFallback(millis);
  675. }
  676. }
  677. /**
  678. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
  679. * draining the macrotask queue until it is empty. The returned value is the milliseconds
  680. * of time that would have been elapsed.
  681. *
  682. * \@publicApi
  683. * @param {?=} maxTurns
  684. * @return {?} The simulated time elapsed, in millis.
  685. *
  686. */
  687. function flush(maxTurns) {
  688. if (fakeAsyncTestModule) {
  689. return fakeAsyncTestModule.flush(maxTurns);
  690. }
  691. else {
  692. return flushFallback(maxTurns);
  693. }
  694. }
  695. /**
  696. * Discard all remaining periodic tasks.
  697. *
  698. * \@publicApi
  699. * @return {?}
  700. */
  701. function discardPeriodicTasks() {
  702. if (fakeAsyncTestModule) {
  703. return fakeAsyncTestModule.discardPeriodicTasks();
  704. }
  705. else {
  706. discardPeriodicTasksFallback();
  707. }
  708. }
  709. /**
  710. * Flush any pending microtasks.
  711. *
  712. * \@publicApi
  713. * @return {?}
  714. */
  715. function flushMicrotasks() {
  716. if (fakeAsyncTestModule) {
  717. return fakeAsyncTestModule.flushMicrotasks();
  718. }
  719. else {
  720. return flushMicrotasksFallback();
  721. }
  722. }
  723. /**
  724. * @fileoverview added by tsickle
  725. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  726. */
  727. /**
  728. * @license
  729. * Copyright Google Inc. All Rights Reserved.
  730. *
  731. * Use of this source code is governed by an MIT-style license that can be
  732. * found in the LICENSE file at https://angular.io/license
  733. */
  734. /**
  735. * Injectable completer that allows signaling completion of an asynchronous test. Used internally.
  736. */
  737. class AsyncTestCompleter {
  738. constructor() {
  739. this._promise = new Promise((/**
  740. * @param {?} res
  741. * @param {?} rej
  742. * @return {?}
  743. */
  744. (res, rej) => {
  745. this._resolve = res;
  746. this._reject = rej;
  747. }));
  748. }
  749. /**
  750. * @param {?=} value
  751. * @return {?}
  752. */
  753. done(value) { this._resolve(value); }
  754. /**
  755. * @param {?=} error
  756. * @param {?=} stackTrace
  757. * @return {?}
  758. */
  759. fail(error, stackTrace) { this._reject(error); }
  760. /**
  761. * @return {?}
  762. */
  763. get promise() { return this._promise; }
  764. }
  765. /**
  766. * @fileoverview added by tsickle
  767. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  768. */
  769. /**
  770. * An abstract class for inserting the root test component element in a platform independent way.
  771. *
  772. * \@publicApi
  773. */
  774. class TestComponentRenderer {
  775. /**
  776. * @param {?} rootElementId
  777. * @return {?}
  778. */
  779. insertRootElement(rootElementId) { }
  780. }
  781. /**
  782. * \@publicApi
  783. * @type {?}
  784. */
  785. const ComponentFixtureAutoDetect = new InjectionToken('ComponentFixtureAutoDetect');
  786. /**
  787. * \@publicApi
  788. * @type {?}
  789. */
  790. const ComponentFixtureNoNgZone = new InjectionToken('ComponentFixtureNoNgZone');
  791. /**
  792. * @fileoverview added by tsickle
  793. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  794. */
  795. /**
  796. * @license
  797. * Copyright Google Inc. All Rights Reserved.
  798. *
  799. * Use of this source code is governed by an MIT-style license that can be
  800. * found in the LICENSE file at https://angular.io/license
  801. */
  802. /**
  803. * Used to resolve resource URLs on `\@Component` when used with JIT compilation.
  804. *
  805. * Example:
  806. * ```
  807. * \@Component({
  808. * selector: 'my-comp',
  809. * templateUrl: 'my-comp.html', // This requires asynchronous resolution
  810. * })
  811. * class MyComponent{
  812. * }
  813. *
  814. * // Calling `renderComponent` will fail because `renderComponent` is a synchronous process
  815. * // and `MyComponent`'s `\@Component.templateUrl` needs to be resolved asynchronously.
  816. *
  817. * // Calling `resolveComponentResources()` will resolve `\@Component.templateUrl` into
  818. * // `\@Component.template`, which allows `renderComponent` to proceed in a synchronous manner.
  819. *
  820. * // Use browser's `fetch()` function as the default resource resolution strategy.
  821. * resolveComponentResources(fetch).then(() => {
  822. * // After resolution all URLs have been converted into `template` strings.
  823. * renderComponent(MyComponent);
  824. * });
  825. *
  826. * ```
  827. *
  828. * NOTE: In AOT the resolution happens during compilation, and so there should be no need
  829. * to call this method outside JIT mode.
  830. *
  831. * @param {?} resourceResolver a function which is responsible for returning a `Promise` to the
  832. * contents of the resolved URL. Browser's `fetch()` method is a good default implementation.
  833. * @return {?}
  834. */
  835. function resolveComponentResources(resourceResolver) {
  836. // Store all promises which are fetching the resources.
  837. /** @type {?} */
  838. const componentResolved = [];
  839. // Cache so that we don't fetch the same resource more than once.
  840. /** @type {?} */
  841. const urlMap = new Map();
  842. /**
  843. * @param {?} url
  844. * @return {?}
  845. */
  846. function cachedResourceResolve(url) {
  847. /** @type {?} */
  848. let promise = urlMap.get(url);
  849. if (!promise) {
  850. /** @type {?} */
  851. const resp = resourceResolver(url);
  852. urlMap.set(url, promise = resp.then(unwrapResponse));
  853. }
  854. return promise;
  855. }
  856. componentResourceResolutionQueue.forEach((/**
  857. * @param {?} component
  858. * @param {?} type
  859. * @return {?}
  860. */
  861. (component, type) => {
  862. /** @type {?} */
  863. const promises = [];
  864. if (component.templateUrl) {
  865. promises.push(cachedResourceResolve(component.templateUrl).then((/**
  866. * @param {?} template
  867. * @return {?}
  868. */
  869. (template) => {
  870. component.template = template;
  871. })));
  872. }
  873. /** @type {?} */
  874. const styleUrls = component.styleUrls;
  875. /** @type {?} */
  876. const styles = component.styles || (component.styles = []);
  877. /** @type {?} */
  878. const styleOffset = component.styles.length;
  879. styleUrls && styleUrls.forEach((/**
  880. * @param {?} styleUrl
  881. * @param {?} index
  882. * @return {?}
  883. */
  884. (styleUrl, index) => {
  885. styles.push(''); // pre-allocate array.
  886. promises.push(cachedResourceResolve(styleUrl).then((/**
  887. * @param {?} style
  888. * @return {?}
  889. */
  890. (style) => {
  891. styles[styleOffset + index] = style;
  892. styleUrls.splice(styleUrls.indexOf(styleUrl), 1);
  893. if (styleUrls.length == 0) {
  894. component.styleUrls = undefined;
  895. }
  896. })));
  897. }));
  898. /** @type {?} */
  899. const fullyResolved = Promise.all(promises).then((/**
  900. * @return {?}
  901. */
  902. () => componentDefResolved(type)));
  903. componentResolved.push(fullyResolved);
  904. }));
  905. clearResolutionOfComponentResourcesQueue();
  906. return Promise.all(componentResolved).then((/**
  907. * @return {?}
  908. */
  909. () => undefined));
  910. }
  911. /** @type {?} */
  912. let componentResourceResolutionQueue = new Map();
  913. // Track when existing ngComponentDef for a Type is waiting on resources.
  914. /** @type {?} */
  915. const componentDefPendingResolution = new Set();
  916. /**
  917. * @param {?} type
  918. * @return {?}
  919. */
  920. function isComponentDefPendingResolution(type) {
  921. return componentDefPendingResolution.has(type);
  922. }
  923. /**
  924. * @return {?}
  925. */
  926. function clearResolutionOfComponentResourcesQueue() {
  927. /** @type {?} */
  928. const old = componentResourceResolutionQueue;
  929. componentResourceResolutionQueue = new Map();
  930. return old;
  931. }
  932. /**
  933. * @param {?} queue
  934. * @return {?}
  935. */
  936. function restoreComponentResolutionQueue(queue) {
  937. componentDefPendingResolution.clear();
  938. queue.forEach((/**
  939. * @param {?} _
  940. * @param {?} type
  941. * @return {?}
  942. */
  943. (_, type) => componentDefPendingResolution.add(type)));
  944. componentResourceResolutionQueue = queue;
  945. }
  946. /**
  947. * @param {?} response
  948. * @return {?}
  949. */
  950. function unwrapResponse(response) {
  951. return typeof response == 'string' ? response : response.text();
  952. }
  953. /**
  954. * @param {?} type
  955. * @return {?}
  956. */
  957. function componentDefResolved(type) {
  958. componentDefPendingResolution.delete(type);
  959. }
  960. /**
  961. * @fileoverview added by tsickle
  962. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  963. */
  964. /** @type {?} */
  965. let _nextReferenceId = 0;
  966. class MetadataOverrider {
  967. constructor() {
  968. this._references = new Map();
  969. }
  970. /**
  971. * Creates a new instance for the given metadata class
  972. * based on an old instance and overrides.
  973. * @template C, T
  974. * @param {?} metadataClass
  975. * @param {?} oldMetadata
  976. * @param {?} override
  977. * @return {?}
  978. */
  979. overrideMetadata(metadataClass, oldMetadata, override) {
  980. /** @type {?} */
  981. const props = {};
  982. if (oldMetadata) {
  983. _valueProps(oldMetadata).forEach((/**
  984. * @param {?} prop
  985. * @return {?}
  986. */
  987. (prop) => props[prop] = ((/** @type {?} */ (oldMetadata)))[prop]));
  988. }
  989. if (override.set) {
  990. if (override.remove || override.add) {
  991. throw new Error(`Cannot set and add/remove ${ɵstringify(metadataClass)} at the same time!`);
  992. }
  993. setMetadata(props, override.set);
  994. }
  995. if (override.remove) {
  996. removeMetadata(props, override.remove, this._references);
  997. }
  998. if (override.add) {
  999. addMetadata(props, override.add);
  1000. }
  1001. return new metadataClass((/** @type {?} */ (props)));
  1002. }
  1003. }
  1004. /**
  1005. * @param {?} metadata
  1006. * @param {?} remove
  1007. * @param {?} references
  1008. * @return {?}
  1009. */
  1010. function removeMetadata(metadata, remove, references) {
  1011. /** @type {?} */
  1012. const removeObjects = new Set();
  1013. for (const prop in remove) {
  1014. /** @type {?} */
  1015. const removeValue = remove[prop];
  1016. if (removeValue instanceof Array) {
  1017. removeValue.forEach((/**
  1018. * @param {?} value
  1019. * @return {?}
  1020. */
  1021. (value) => { removeObjects.add(_propHashKey(prop, value, references)); }));
  1022. }
  1023. else {
  1024. removeObjects.add(_propHashKey(prop, removeValue, references));
  1025. }
  1026. }
  1027. for (const prop in metadata) {
  1028. /** @type {?} */
  1029. const propValue = metadata[prop];
  1030. if (propValue instanceof Array) {
  1031. metadata[prop] = propValue.filter((/**
  1032. * @param {?} value
  1033. * @return {?}
  1034. */
  1035. (value) => !removeObjects.has(_propHashKey(prop, value, references))));
  1036. }
  1037. else {
  1038. if (removeObjects.has(_propHashKey(prop, propValue, references))) {
  1039. metadata[prop] = undefined;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. /**
  1045. * @param {?} metadata
  1046. * @param {?} add
  1047. * @return {?}
  1048. */
  1049. function addMetadata(metadata, add) {
  1050. for (const prop in add) {
  1051. /** @type {?} */
  1052. const addValue = add[prop];
  1053. /** @type {?} */
  1054. const propValue = metadata[prop];
  1055. if (propValue != null && propValue instanceof Array) {
  1056. metadata[prop] = propValue.concat(addValue);
  1057. }
  1058. else {
  1059. metadata[prop] = addValue;
  1060. }
  1061. }
  1062. }
  1063. /**
  1064. * @param {?} metadata
  1065. * @param {?} set
  1066. * @return {?}
  1067. */
  1068. function setMetadata(metadata, set) {
  1069. for (const prop in set) {
  1070. metadata[prop] = set[prop];
  1071. }
  1072. }
  1073. /**
  1074. * @param {?} propName
  1075. * @param {?} propValue
  1076. * @param {?} references
  1077. * @return {?}
  1078. */
  1079. function _propHashKey(propName, propValue, references) {
  1080. /** @type {?} */
  1081. const replacer = (/**
  1082. * @param {?} key
  1083. * @param {?} value
  1084. * @return {?}
  1085. */
  1086. (key, value) => {
  1087. if (typeof value === 'function') {
  1088. value = _serializeReference(value, references);
  1089. }
  1090. return value;
  1091. });
  1092. return `${propName}:${JSON.stringify(propValue, replacer)}`;
  1093. }
  1094. /**
  1095. * @param {?} ref
  1096. * @param {?} references
  1097. * @return {?}
  1098. */
  1099. function _serializeReference(ref, references) {
  1100. /** @type {?} */
  1101. let id = references.get(ref);
  1102. if (!id) {
  1103. id = `${ɵstringify(ref)}${_nextReferenceId++}`;
  1104. references.set(ref, id);
  1105. }
  1106. return id;
  1107. }
  1108. /**
  1109. * @param {?} obj
  1110. * @return {?}
  1111. */
  1112. function _valueProps(obj) {
  1113. /** @type {?} */
  1114. const props = [];
  1115. // regular public props
  1116. Object.keys(obj).forEach((/**
  1117. * @param {?} prop
  1118. * @return {?}
  1119. */
  1120. (prop) => {
  1121. if (!prop.startsWith('_')) {
  1122. props.push(prop);
  1123. }
  1124. }));
  1125. // getters
  1126. /** @type {?} */
  1127. let proto = obj;
  1128. while (proto = Object.getPrototypeOf(proto)) {
  1129. Object.keys(proto).forEach((/**
  1130. * @param {?} protoProp
  1131. * @return {?}
  1132. */
  1133. (protoProp) => {
  1134. /** @type {?} */
  1135. const desc = Object.getOwnPropertyDescriptor(proto, protoProp);
  1136. if (!protoProp.startsWith('_') && desc && 'get' in desc) {
  1137. props.push(protoProp);
  1138. }
  1139. }));
  1140. }
  1141. return props;
  1142. }
  1143. /**
  1144. * @fileoverview added by tsickle
  1145. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1146. */
  1147. /** @type {?} */
  1148. const reflection = new ɵReflectionCapabilities();
  1149. /**
  1150. * Allows to override ivy metadata for tests (via the `TestBed`).
  1151. * @abstract
  1152. * @template T
  1153. */
  1154. class OverrideResolver {
  1155. constructor() {
  1156. this.overrides = new Map();
  1157. this.resolved = new Map();
  1158. }
  1159. /**
  1160. * @param {?} type
  1161. * @param {?} override
  1162. * @return {?}
  1163. */
  1164. addOverride(type, override) {
  1165. /** @type {?} */
  1166. const overrides = this.overrides.get(type) || [];
  1167. overrides.push(override);
  1168. this.overrides.set(type, overrides);
  1169. this.resolved.delete(type);
  1170. }
  1171. /**
  1172. * @param {?} overrides
  1173. * @return {?}
  1174. */
  1175. setOverrides(overrides) {
  1176. this.overrides.clear();
  1177. overrides.forEach((/**
  1178. * @param {?} __0
  1179. * @return {?}
  1180. */
  1181. ([type, override]) => { this.addOverride(type, override); }));
  1182. }
  1183. /**
  1184. * @param {?} type
  1185. * @return {?}
  1186. */
  1187. getAnnotation(type) {
  1188. /** @type {?} */
  1189. const annotations = reflection.annotations(type);
  1190. // Try to find the nearest known Type annotation and make sure that this annotation is an
  1191. // instance of the type we are looking for, so we can use it for resolution. Note: there might
  1192. // be multiple known annotations found due to the fact that Components can extend Directives (so
  1193. // both Directive and Component annotations would be present), so we always check if the known
  1194. // annotation has the right type.
  1195. for (let i = annotations.length - 1; i >= 0; i--) {
  1196. /** @type {?} */
  1197. const annotation = annotations[i];
  1198. /** @type {?} */
  1199. const isKnownType = annotation instanceof Directive || annotation instanceof Component ||
  1200. annotation instanceof Pipe || annotation instanceof NgModule;
  1201. if (isKnownType) {
  1202. return annotation instanceof this.type ? annotation : null;
  1203. }
  1204. }
  1205. return null;
  1206. }
  1207. /**
  1208. * @param {?} type
  1209. * @return {?}
  1210. */
  1211. resolve(type) {
  1212. /** @type {?} */
  1213. let resolved = this.resolved.get(type) || null;
  1214. if (!resolved) {
  1215. resolved = this.getAnnotation(type);
  1216. if (resolved) {
  1217. /** @type {?} */
  1218. const overrides = this.overrides.get(type);
  1219. if (overrides) {
  1220. /** @type {?} */
  1221. const overrider = new MetadataOverrider();
  1222. overrides.forEach((/**
  1223. * @param {?} override
  1224. * @return {?}
  1225. */
  1226. override => {
  1227. resolved = overrider.overrideMetadata(this.type, (/** @type {?} */ (resolved)), override);
  1228. }));
  1229. }
  1230. }
  1231. this.resolved.set(type, resolved);
  1232. }
  1233. return resolved;
  1234. }
  1235. }
  1236. class DirectiveResolver extends OverrideResolver {
  1237. /**
  1238. * @return {?}
  1239. */
  1240. get type() { return Directive; }
  1241. }
  1242. class ComponentResolver extends OverrideResolver {
  1243. /**
  1244. * @return {?}
  1245. */
  1246. get type() { return Component; }
  1247. }
  1248. class PipeResolver extends OverrideResolver {
  1249. /**
  1250. * @return {?}
  1251. */
  1252. get type() { return Pipe; }
  1253. }
  1254. class NgModuleResolver extends OverrideResolver {
  1255. /**
  1256. * @return {?}
  1257. */
  1258. get type() { return NgModule; }
  1259. }
  1260. /**
  1261. * @fileoverview added by tsickle
  1262. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1263. */
  1264. /** @enum {number} */
  1265. const TestingModuleOverride = {
  1266. DECLARATION: 0,
  1267. OVERRIDE_TEMPLATE: 1,
  1268. };
  1269. TestingModuleOverride[TestingModuleOverride.DECLARATION] = 'DECLARATION';
  1270. TestingModuleOverride[TestingModuleOverride.OVERRIDE_TEMPLATE] = 'OVERRIDE_TEMPLATE';
  1271. /**
  1272. * @param {?} value
  1273. * @return {?}
  1274. */
  1275. function isTestingModuleOverride(value) {
  1276. return value === TestingModuleOverride.DECLARATION ||
  1277. value === TestingModuleOverride.OVERRIDE_TEMPLATE;
  1278. }
  1279. class R3TestBedCompiler {
  1280. /**
  1281. * @param {?} platform
  1282. * @param {?} additionalModuleTypes
  1283. */
  1284. constructor(platform, additionalModuleTypes) {
  1285. this.platform = platform;
  1286. this.additionalModuleTypes = additionalModuleTypes;
  1287. this.originalComponentResolutionQueue = null;
  1288. // Testing module configuration
  1289. this.declarations = [];
  1290. this.imports = [];
  1291. this.providers = [];
  1292. this.schemas = [];
  1293. // Queues of components/directives/pipes that should be recompiled.
  1294. this.pendingComponents = new Set();
  1295. this.pendingDirectives = new Set();
  1296. this.pendingPipes = new Set();
  1297. // Keep track of all components and directives, so we can patch Providers onto defs later.
  1298. this.seenComponents = new Set();
  1299. this.seenDirectives = new Set();
  1300. // Store resolved styles for Components that have template overrides present and `styleUrls`
  1301. // defined at the same time.
  1302. this.existingComponentStyles = new Map();
  1303. this.resolvers = initResolvers();
  1304. this.componentToModuleScope = new Map();
  1305. // Map that keeps initial version of component/directive/pipe defs in case
  1306. // we compile a Type again, thus overriding respective static fields. This is
  1307. // required to make sure we restore defs to their initial states between test runs
  1308. // TODO: we should support the case with multiple defs on a type
  1309. this.initialNgDefs = new Map();
  1310. // Array that keeps cleanup operations for initial versions of component/directive/pipe/module
  1311. // defs in case TestBed makes changes to the originals.
  1312. this.defCleanupOps = [];
  1313. this._injector = null;
  1314. this.compilerProviders = null;
  1315. this.providerOverrides = [];
  1316. this.rootProviderOverrides = [];
  1317. this.providerOverridesByToken = new Map();
  1318. this.moduleProvidersOverridden = new Set();
  1319. this.testModuleRef = null;
  1320. class DynamicTestModule {
  1321. }
  1322. this.testModuleType = (/** @type {?} */ (DynamicTestModule));
  1323. }
  1324. /**
  1325. * @param {?} providers
  1326. * @return {?}
  1327. */
  1328. setCompilerProviders(providers) {
  1329. this.compilerProviders = providers;
  1330. this._injector = null;
  1331. }
  1332. /**
  1333. * @param {?} moduleDef
  1334. * @return {?}
  1335. */
  1336. configureTestingModule(moduleDef) {
  1337. // Enqueue any compilation tasks for the directly declared component.
  1338. if (moduleDef.declarations !== undefined) {
  1339. this.queueTypeArray(moduleDef.declarations, TestingModuleOverride.DECLARATION);
  1340. this.declarations.push(...moduleDef.declarations);
  1341. }
  1342. // Enqueue any compilation tasks for imported modules.
  1343. if (moduleDef.imports !== undefined) {
  1344. this.queueTypesFromModulesArray(moduleDef.imports);
  1345. this.imports.push(...moduleDef.imports);
  1346. }
  1347. if (moduleDef.providers !== undefined) {
  1348. this.providers.push(...moduleDef.providers);
  1349. }
  1350. if (moduleDef.schemas !== undefined) {
  1351. this.schemas.push(...moduleDef.schemas);
  1352. }
  1353. }
  1354. /**
  1355. * @param {?} ngModule
  1356. * @param {?} override
  1357. * @return {?}
  1358. */
  1359. overrideModule(ngModule, override) {
  1360. // Compile the module right away.
  1361. this.resolvers.module.addOverride(ngModule, override);
  1362. /** @type {?} */
  1363. const metadata = this.resolvers.module.resolve(ngModule);
  1364. if (metadata === null) {
  1365. throw new Error(`${ngModule.name} is not an @NgModule or is missing metadata`);
  1366. }
  1367. this.recompileNgModule(ngModule);
  1368. // At this point, the module has a valid .ngModuleDef, but the override may have introduced
  1369. // new declarations or imported modules. Ingest any possible new types and add them to the
  1370. // current queue.
  1371. this.queueTypesFromModulesArray([ngModule]);
  1372. }
  1373. /**
  1374. * @param {?} component
  1375. * @param {?} override
  1376. * @return {?}
  1377. */
  1378. overrideComponent(component, override) {
  1379. this.resolvers.component.addOverride(component, override);
  1380. this.pendingComponents.add(component);
  1381. }
  1382. /**
  1383. * @param {?} directive
  1384. * @param {?} override
  1385. * @return {?}
  1386. */
  1387. overrideDirective(directive, override) {
  1388. this.resolvers.directive.addOverride(directive, override);
  1389. this.pendingDirectives.add(directive);
  1390. }
  1391. /**
  1392. * @param {?} pipe
  1393. * @param {?} override
  1394. * @return {?}
  1395. */
  1396. overridePipe(pipe, override) {
  1397. this.resolvers.pipe.addOverride(pipe, override);
  1398. this.pendingPipes.add(pipe);
  1399. }
  1400. /**
  1401. * @param {?} token
  1402. * @param {?} provider
  1403. * @return {?}
  1404. */
  1405. overrideProvider(token, provider) {
  1406. /** @type {?} */
  1407. const providerDef = provider.useFactory ?
  1408. {
  1409. provide: token,
  1410. useFactory: provider.useFactory,
  1411. deps: provider.deps || [],
  1412. multi: provider.multi,
  1413. } :
  1414. { provide: token, useValue: provider.useValue, multi: provider.multi };
  1415. /** @type {?} */
  1416. let injectableDef;
  1417. /** @type {?} */
  1418. const isRoot = (typeof token !== 'string' && (injectableDef = ɵgetInjectableDef(token)) &&
  1419. injectableDef.providedIn === 'root');
  1420. /** @type {?} */
  1421. const overridesBucket = isRoot ? this.rootProviderOverrides : this.providerOverrides;
  1422. overridesBucket.push(providerDef);
  1423. // Keep overrides grouped by token as well for fast lookups using token
  1424. this.providerOverridesByToken.set(token, providerDef);
  1425. }
  1426. /**
  1427. * @param {?} type
  1428. * @param {?} template
  1429. * @return {?}
  1430. */
  1431. overrideTemplateUsingTestingModule(type, template) {
  1432. /** @type {?} */
  1433. const def = ((/** @type {?} */ (type)))[ɵNG_COMPONENT_DEF];
  1434. /** @type {?} */
  1435. const hasStyleUrls = (/**
  1436. * @return {?}
  1437. */
  1438. () => {
  1439. /** @type {?} */
  1440. const metadata = (/** @type {?} */ ((/** @type {?} */ (this.resolvers.component.resolve(type)))));
  1441. return !!metadata.styleUrls && metadata.styleUrls.length > 0;
  1442. });
  1443. /** @type {?} */
  1444. const overrideStyleUrls = !!def && !isComponentDefPendingResolution(type) && hasStyleUrls();
  1445. // In Ivy, compiling a component does not require knowing the module providing the
  1446. // component's scope, so overrideTemplateUsingTestingModule can be implemented purely via
  1447. // overrideComponent. Important: overriding template requires full Component re-compilation,
  1448. // which may fail in case styleUrls are also present (thus Component is considered as required
  1449. // resolution). In order to avoid this, we preemptively set styleUrls to an empty array,
  1450. // preserve current styles available on Component def and restore styles back once compilation
  1451. // is complete.
  1452. /** @type {?} */
  1453. const override = overrideStyleUrls ? { template, styles: [], styleUrls: [] } : { template };
  1454. this.overrideComponent(type, { set: override });
  1455. if (overrideStyleUrls && def.styles && def.styles.length > 0) {
  1456. this.existingComponentStyles.set(type, def.styles);
  1457. }
  1458. // Set the component's scope to be the testing module.
  1459. this.componentToModuleScope.set(type, TestingModuleOverride.OVERRIDE_TEMPLATE);
  1460. }
  1461. /**
  1462. * @return {?}
  1463. */
  1464. compileComponents() {
  1465. return __awaiter(this, void 0, void 0, function* () {
  1466. this.clearComponentResolutionQueue();
  1467. // Run compilers for all queued types.
  1468. /** @type {?} */
  1469. let needsAsyncResources = this.compileTypesSync();
  1470. // compileComponents() should not be async unless it needs to be.
  1471. if (needsAsyncResources) {
  1472. /** @type {?} */
  1473. let resourceLoader;
  1474. /** @type {?} */
  1475. let resolver = (/**
  1476. * @param {?} url
  1477. * @return {?}
  1478. */
  1479. (url) => {
  1480. if (!resourceLoader) {
  1481. resourceLoader = this.injector.get(ResourceLoader);
  1482. }
  1483. return Promise.resolve(resourceLoader.get(url));
  1484. });
  1485. yield resolveComponentResources(resolver);
  1486. }
  1487. });
  1488. }
  1489. /**
  1490. * @return {?}
  1491. */
  1492. finalize() {
  1493. // One last compile
  1494. this.compileTypesSync();
  1495. // Create the testing module itself.
  1496. this.compileTestModule();
  1497. this.applyTransitiveScopes();
  1498. this.applyProviderOverrides();
  1499. // Patch previously stored `styles` Component values (taken from ngComponentDef), in case these
  1500. // Components have `styleUrls` fields defined and template override was requested.
  1501. this.patchComponentsWithExistingStyles();
  1502. // Clear the componentToModuleScope map, so that future compilations don't reset the scope of
  1503. // every component.
  1504. this.componentToModuleScope.clear();
  1505. /** @type {?} */
  1506. const parentInjector = this.platform.injector;
  1507. this.testModuleRef = new ɵRender3NgModuleRef(this.testModuleType, parentInjector);
  1508. // Set the locale ID, it can be overridden for the tests
  1509. /** @type {?} */
  1510. const localeId = this.testModuleRef.injector.get(LOCALE_ID, ɵDEFAULT_LOCALE_ID);
  1511. ɵsetLocaleId(localeId);
  1512. // ApplicationInitStatus.runInitializers() is marked @internal to core.
  1513. // Cast it to any before accessing it.
  1514. ((/** @type {?} */ (this.testModuleRef.injector.get(ApplicationInitStatus)))).runInitializers();
  1515. return this.testModuleRef;
  1516. }
  1517. /**
  1518. * \@internal
  1519. * @param {?} moduleType
  1520. * @return {?}
  1521. */
  1522. _compileNgModuleSync(moduleType) {
  1523. this.queueTypesFromModulesArray([moduleType]);
  1524. this.compileTypesSync();
  1525. this.applyProviderOverrides();
  1526. this.applyProviderOverridesToModule(moduleType);
  1527. this.applyTransitiveScopes();
  1528. }
  1529. /**
  1530. * \@internal
  1531. * @param {?} moduleType
  1532. * @return {?}
  1533. */
  1534. _compileNgModuleAsync(moduleType) {
  1535. return __awaiter(this, void 0, void 0, function* () {
  1536. this.queueTypesFromModulesArray([moduleType]);
  1537. yield this.compileComponents();
  1538. this.applyProviderOverrides();
  1539. this.applyProviderOverridesToModule(moduleType);
  1540. this.applyTransitiveScopes();
  1541. });
  1542. }
  1543. /**
  1544. * \@internal
  1545. * @return {?}
  1546. */
  1547. _getModuleResolver() { return this.resolvers.module; }
  1548. /**
  1549. * \@internal
  1550. * @param {?} moduleType
  1551. * @return {?}
  1552. */
  1553. _getComponentFactories(moduleType) {
  1554. return maybeUnwrapFn(moduleType.ngModuleDef.declarations).reduce((/**
  1555. * @param {?} factories
  1556. * @param {?} declaration
  1557. * @return {?}
  1558. */
  1559. (factories, declaration) => {
  1560. /** @nocollapse @type {?} */
  1561. const componentDef = ((/** @type {?} */ (declaration))).ngComponentDef;
  1562. componentDef && factories.push(new ɵRender3ComponentFactory(componentDef, (/** @type {?} */ (this.testModuleRef))));
  1563. return factories;
  1564. }), (/** @type {?} */ ([])));
  1565. }
  1566. /**
  1567. * @private
  1568. * @return {?}
  1569. */
  1570. compileTypesSync() {
  1571. // Compile all queued components, directives, pipes.
  1572. /** @type {?} */
  1573. let needsAsyncResources = false;
  1574. this.pendingComponents.forEach((/**
  1575. * @param {?} declaration
  1576. * @return {?}
  1577. */
  1578. declaration => {
  1579. needsAsyncResources = needsAsyncResources || isComponentDefPendingResolution(declaration);
  1580. /** @type {?} */
  1581. const metadata = (/** @type {?} */ (this.resolvers.component.resolve(declaration)));
  1582. this.maybeStoreNgDef(ɵNG_COMPONENT_DEF, declaration);
  1583. ɵcompileComponent(declaration, metadata);
  1584. }));
  1585. this.pendingComponents.clear();
  1586. this.pendingDirectives.forEach((/**
  1587. * @param {?} declaration
  1588. * @return {?}
  1589. */
  1590. declaration => {
  1591. /** @type {?} */
  1592. const metadata = (/** @type {?} */ (this.resolvers.directive.resolve(declaration)));
  1593. this.maybeStoreNgDef(ɵNG_DIRECTIVE_DEF, declaration);
  1594. ɵcompileDirective(declaration, metadata);
  1595. }));
  1596. this.pendingDirectives.clear();
  1597. this.pendingPipes.forEach((/**
  1598. * @param {?} declaration
  1599. * @return {?}
  1600. */
  1601. declaration => {
  1602. /** @type {?} */
  1603. const metadata = (/** @type {?} */ (this.resolvers.pipe.resolve(declaration)));
  1604. this.maybeStoreNgDef(ɵNG_PIPE_DEF, declaration);
  1605. ɵcompilePipe(declaration, metadata);
  1606. }));
  1607. this.pendingPipes.clear();
  1608. return needsAsyncResources;
  1609. }
  1610. /**
  1611. * @private
  1612. * @return {?}
  1613. */
  1614. applyTransitiveScopes() {
  1615. /** @type {?} */
  1616. const moduleToScope = new Map();
  1617. /** @type {?} */
  1618. const getScopeOfModule = (/**
  1619. * @param {?} moduleType
  1620. * @return {?}
  1621. */
  1622. (moduleType) => {
  1623. if (!moduleToScope.has(moduleType)) {
  1624. /** @type {?} */
  1625. const realType = isTestingModuleOverride(moduleType) ? this.testModuleType : moduleType;
  1626. moduleToScope.set(moduleType, ɵtransitiveScopesFor(realType));
  1627. }
  1628. return (/** @type {?} */ (moduleToScope.get(moduleType)));
  1629. });
  1630. this.componentToModuleScope.forEach((/**
  1631. * @param {?} moduleType
  1632. * @param {?} componentType
  1633. * @return {?}
  1634. */
  1635. (moduleType, componentType) => {
  1636. /** @type {?} */
  1637. const moduleScope = getScopeOfModule(moduleType);
  1638. this.storeFieldOfDefOnType(componentType, ɵNG_COMPONENT_DEF, 'directiveDefs');
  1639. this.storeFieldOfDefOnType(componentType, ɵNG_COMPONENT_DEF, 'pipeDefs');
  1640. ɵpatchComponentDefWithScope(((/** @type {?} */ (componentType))).ngComponentDef, moduleScope);
  1641. }));
  1642. this.componentToModuleScope.clear();
  1643. }
  1644. /**
  1645. * @private
  1646. * @return {?}
  1647. */
  1648. applyProviderOverrides() {
  1649. /** @type {?} */
  1650. const maybeApplyOverrides = (/**
  1651. * @param {?} field
  1652. * @return {?}
  1653. */
  1654. (field) => (/**
  1655. * @param {?} type
  1656. * @return {?}
  1657. */
  1658. (type) => {
  1659. /** @type {?} */
  1660. const resolver = field === ɵNG_COMPONENT_DEF ? this.resolvers.component : this.resolvers.directive;
  1661. /** @type {?} */
  1662. const metadata = (/** @type {?} */ (resolver.resolve(type)));
  1663. if (this.hasProviderOverrides(metadata.providers)) {
  1664. this.patchDefWithProviderOverrides(type, field);
  1665. }
  1666. }));
  1667. this.seenComponents.forEach(maybeApplyOverrides(ɵNG_COMPONENT_DEF));
  1668. this.seenDirectives.forEach(maybeApplyOverrides(ɵNG_DIRECTIVE_DEF));
  1669. this.seenComponents.clear();
  1670. this.seenDirectives.clear();
  1671. }
  1672. /**
  1673. * @private
  1674. * @param {?} moduleType
  1675. * @return {?}
  1676. */
  1677. applyProviderOverridesToModule(moduleType) {
  1678. if (this.moduleProvidersOverridden.has(moduleType)) {
  1679. return;
  1680. }
  1681. this.moduleProvidersOverridden.add(moduleType);
  1682. /** @type {?} */
  1683. const injectorDef = ((/** @type {?} */ (moduleType)))[ɵNG_INJECTOR_DEF];
  1684. if (this.providerOverridesByToken.size > 0) {
  1685. if (this.hasProviderOverrides(injectorDef.providers)) {
  1686. this.maybeStoreNgDef(ɵNG_INJECTOR_DEF, moduleType);
  1687. this.storeFieldOfDefOnType(moduleType, ɵNG_INJECTOR_DEF, 'providers');
  1688. injectorDef.providers = this.getOverriddenProviders(injectorDef.providers);
  1689. }
  1690. // Apply provider overrides to imported modules recursively
  1691. /** @type {?} */
  1692. const moduleDef = ((/** @type {?} */ (moduleType)))[ɵNG_MODULE_DEF];
  1693. for (const importType of moduleDef.imports) {
  1694. this.applyProviderOverridesToModule(importType);
  1695. }
  1696. }
  1697. }
  1698. /**
  1699. * @private
  1700. * @return {?}
  1701. */
  1702. patchComponentsWithExistingStyles() {
  1703. this.existingComponentStyles.forEach((/**
  1704. * @param {?} styles
  1705. * @param {?} type
  1706. * @return {?}
  1707. */
  1708. (styles, type) => ((/** @type {?} */ (type)))[ɵNG_COMPONENT_DEF].styles = styles));
  1709. this.existingComponentStyles.clear();
  1710. }
  1711. /**
  1712. * @private
  1713. * @param {?} arr
  1714. * @param {?} moduleType
  1715. * @return {?}
  1716. */
  1717. queueTypeArray(arr, moduleType) {
  1718. for (const value of arr) {
  1719. if (Array.isArray(value)) {
  1720. this.queueTypeArray(value, moduleType);
  1721. }
  1722. else {
  1723. this.queueType(value, moduleType);
  1724. }
  1725. }
  1726. }
  1727. /**
  1728. * @private
  1729. * @param {?} ngModule
  1730. * @return {?}
  1731. */
  1732. recompileNgModule(ngModule) {
  1733. /** @type {?} */
  1734. const metadata = this.resolvers.module.resolve(ngModule);
  1735. if (metadata === null) {
  1736. throw new Error(`Unable to resolve metadata for NgModule: ${ngModule.name}`);
  1737. }
  1738. // Cache the initial ngModuleDef as it will be overwritten.
  1739. this.maybeStoreNgDef(ɵNG_MODULE_DEF, ngModule);
  1740. this.maybeStoreNgDef(ɵNG_INJECTOR_DEF, ngModule);
  1741. ɵcompileNgModuleDefs((/** @type {?} */ (ngModule)), metadata);
  1742. }
  1743. /**
  1744. * @private
  1745. * @param {?} type
  1746. * @param {?} moduleType
  1747. * @return {?}
  1748. */
  1749. queueType(type, moduleType) {
  1750. /** @type {?} */
  1751. const component = this.resolvers.component.resolve(type);
  1752. if (component) {
  1753. // Check whether a give Type has respective NG def (ngComponentDef) and compile if def is
  1754. // missing. That might happen in case a class without any Angular decorators extends another
  1755. // class where Component/Directive/Pipe decorator is defined.
  1756. if (isComponentDefPendingResolution(type) || !type.hasOwnProperty(ɵNG_COMPONENT_DEF)) {
  1757. this.pendingComponents.add(type);
  1758. }
  1759. this.seenComponents.add(type);
  1760. // Keep track of the module which declares this component, so later the component's scope
  1761. // can be set correctly. If the component has already been recorded here, then one of several
  1762. // cases is true:
  1763. // * the module containing the component was imported multiple times (common).
  1764. // * the component is declared in multiple modules (which is an error).
  1765. // * the component was in 'declarations' of the testing module, and also in an imported module
  1766. // in which case the module scope will be TestingModuleOverride.DECLARATION.
  1767. // * overrideTemplateUsingTestingModule was called for the component in which case the module
  1768. // scope will be TestingModuleOverride.OVERRIDE_TEMPLATE.
  1769. //
  1770. // If the component was previously in the testing module's 'declarations' (meaning the
  1771. // current value is TestingModuleOverride.DECLARATION), then `moduleType` is the component's
  1772. // real module, which was imported. This pattern is understood to mean that the component
  1773. // should use its original scope, but that the testing module should also contain the
  1774. // component in its scope.
  1775. if (!this.componentToModuleScope.has(type) ||
  1776. this.componentToModuleScope.get(type) === TestingModuleOverride.DECLARATION) {
  1777. this.componentToModuleScope.set(type, moduleType);
  1778. }
  1779. return;
  1780. }
  1781. /** @type {?} */
  1782. const directive = this.resolvers.directive.resolve(type);
  1783. if (directive) {
  1784. if (!type.hasOwnProperty(ɵNG_DIRECTIVE_DEF)) {
  1785. this.pendingDirectives.add(type);
  1786. }
  1787. this.seenDirectives.add(type);
  1788. return;
  1789. }
  1790. /** @type {?} */
  1791. const pipe = this.resolvers.pipe.resolve(type);
  1792. if (pipe && !type.hasOwnProperty(ɵNG_PIPE_DEF)) {
  1793. this.pendingPipes.add(type);
  1794. return;
  1795. }
  1796. }
  1797. /**
  1798. * @private
  1799. * @param {?} arr
  1800. * @return {?}
  1801. */
  1802. queueTypesFromModulesArray(arr) {
  1803. for (const value of arr) {
  1804. if (Array.isArray(value)) {
  1805. this.queueTypesFromModulesArray(value);
  1806. }
  1807. else if (hasNgModuleDef(value)) {
  1808. /** @nocollapse @type {?} */
  1809. const def = value.ngModuleDef;
  1810. // Look through declarations, imports, and exports, and queue everything found there.
  1811. this.queueTypeArray(maybeUnwrapFn(def.declarations), value);
  1812. this.queueTypesFromModulesArray(maybeUnwrapFn(def.imports));
  1813. this.queueTypesFromModulesArray(maybeUnwrapFn(def.exports));
  1814. }
  1815. }
  1816. }
  1817. /**
  1818. * @private
  1819. * @param {?} prop
  1820. * @param {?} type
  1821. * @return {?}
  1822. */
  1823. maybeStoreNgDef(prop, type) {
  1824. if (!this.initialNgDefs.has(type)) {
  1825. /** @type {?} */
  1826. const currentDef = Object.getOwnPropertyDescriptor(type, prop);
  1827. this.initialNgDefs.set(type, [prop, currentDef]);
  1828. }
  1829. }
  1830. /**
  1831. * @private
  1832. * @param {?} type
  1833. * @param {?} defField
  1834. * @param {?} field
  1835. * @return {?}
  1836. */
  1837. storeFieldOfDefOnType(type, defField, field) {
  1838. /** @type {?} */
  1839. const def = ((/** @type {?} */ (type)))[defField];
  1840. /** @type {?} */
  1841. const original = def[field];
  1842. this.defCleanupOps.push({ field, def, original });
  1843. }
  1844. /**
  1845. * Clears current components resolution queue, but stores the state of the queue, so we can
  1846. * restore it later. Clearing the queue is required before we try to compile components (via
  1847. * `TestBed.compileComponents`), so that component defs are in sync with the resolution queue.
  1848. * @private
  1849. * @return {?}
  1850. */
  1851. clearComponentResolutionQueue() {
  1852. if (this.originalComponentResolutionQueue === null) {
  1853. this.originalComponentResolutionQueue = new Map();
  1854. }
  1855. clearResolutionOfComponentResourcesQueue().forEach((/**
  1856. * @param {?} value
  1857. * @param {?} key
  1858. * @return {?}
  1859. */
  1860. (value, key) => (/** @type {?} */ (this.originalComponentResolutionQueue)).set(key, value)));
  1861. }
  1862. /*
  1863. * Restores component resolution queue to the previously saved state. This operation is performed
  1864. * as a part of restoring the state after completion of the current set of tests (that might
  1865. * potentially mutate the state).
  1866. */
  1867. /**
  1868. * @private
  1869. * @return {?}
  1870. */
  1871. restoreComponentResolutionQueue() {
  1872. if (this.originalComponentResolutionQueue !== null) {
  1873. restoreComponentResolutionQueue(this.originalComponentResolutionQueue);
  1874. this.originalComponentResolutionQueue = null;
  1875. }
  1876. }
  1877. /**
  1878. * @return {?}
  1879. */
  1880. restoreOriginalState() {
  1881. for (const op of this.defCleanupOps) {
  1882. op.def[op.field] = op.original;
  1883. }
  1884. // Restore initial component/directive/pipe defs
  1885. this.initialNgDefs.forEach((/**
  1886. * @param {?} value
  1887. * @param {?} type
  1888. * @return {?}
  1889. */
  1890. (value, type) => {
  1891. const [prop, descriptor] = value;
  1892. if (!descriptor) {
  1893. // Delete operations are generally undesirable since they have performance implications
  1894. // on objects they were applied to. In this particular case, situations where this code is
  1895. // invoked should be quite rare to cause any noticable impact, since it's applied only to
  1896. // some test cases (for example when class with no annotations extends some @Component)
  1897. // when we need to clear 'ngComponentDef' field on a given class to restore its original
  1898. // state (before applying overrides and running tests).
  1899. delete ((/** @type {?} */ (type)))[prop];
  1900. }
  1901. else {
  1902. Object.defineProperty(type, prop, descriptor);
  1903. }
  1904. }));
  1905. this.initialNgDefs.clear();
  1906. this.moduleProvidersOverridden.clear();
  1907. this.restoreComponentResolutionQueue();
  1908. // Restore the locale ID to the default value, this shouldn't be necessary but we never know
  1909. ɵsetLocaleId(ɵDEFAULT_LOCALE_ID);
  1910. }
  1911. /**
  1912. * @private
  1913. * @return {?}
  1914. */
  1915. compileTestModule() {
  1916. class RootScopeModule {
  1917. }
  1918. ɵcompileNgModuleDefs((/** @type {?} */ (RootScopeModule)), {
  1919. providers: [...this.rootProviderOverrides],
  1920. });
  1921. /** @type {?} */
  1922. const ngZone = new NgZone({ enableLongStackTrace: true });
  1923. /** @type {?} */
  1924. const providers = [
  1925. { provide: NgZone, useValue: ngZone },
  1926. { provide: Compiler, useFactory: (/**
  1927. * @return {?}
  1928. */
  1929. () => new R3TestCompiler(this)) },
  1930. ...this.providers,
  1931. ...this.providerOverrides,
  1932. ];
  1933. /** @type {?} */
  1934. const imports = [RootScopeModule, this.additionalModuleTypes, this.imports || []];
  1935. // clang-format off
  1936. ɵcompileNgModuleDefs(this.testModuleType, {
  1937. declarations: this.declarations,
  1938. imports,
  1939. schemas: this.schemas,
  1940. providers,
  1941. }, /* allowDuplicateDeclarationsInRoot */ true);
  1942. // clang-format on
  1943. this.applyProviderOverridesToModule(this.testModuleType);
  1944. }
  1945. /**
  1946. * @return {?}
  1947. */
  1948. get injector() {
  1949. if (this._injector !== null) {
  1950. return this._injector;
  1951. }
  1952. /** @type {?} */
  1953. const providers = [];
  1954. /** @type {?} */
  1955. const compilerOptions = this.platform.injector.get(COMPILER_OPTIONS);
  1956. compilerOptions.forEach((/**
  1957. * @param {?} opts
  1958. * @return {?}
  1959. */
  1960. opts => {
  1961. if (opts.providers) {
  1962. providers.push(opts.providers);
  1963. }
  1964. }));
  1965. if (this.compilerProviders !== null) {
  1966. providers.push(...this.compilerProviders);
  1967. }
  1968. // TODO(ocombe): make this work with an Injector directly instead of creating a module for it
  1969. class CompilerModule {
  1970. }
  1971. ɵcompileNgModuleDefs((/** @type {?} */ (CompilerModule)), { providers });
  1972. /** @type {?} */
  1973. const CompilerModuleFactory = new ɵNgModuleFactory(CompilerModule);
  1974. this._injector = CompilerModuleFactory.create(this.platform.injector).injector;
  1975. return this._injector;
  1976. }
  1977. // get overrides for a specific provider (if any)
  1978. /**
  1979. * @private
  1980. * @param {?} provider
  1981. * @return {?}
  1982. */
  1983. getSingleProviderOverrides(provider) {
  1984. /** @type {?} */
  1985. const token = getProviderToken(provider);
  1986. return this.providerOverridesByToken.get(token) || null;
  1987. }
  1988. /**
  1989. * @private
  1990. * @param {?=} providers
  1991. * @return {?}
  1992. */
  1993. getProviderOverrides(providers) {
  1994. if (!providers || !providers.length || this.providerOverridesByToken.size === 0)
  1995. return [];
  1996. // There are two flattening operations here. The inner flatten() operates on the metadata's
  1997. // providers and applies a mapping function which retrieves overrides for each incoming
  1998. // provider. The outer flatten() then flattens the produced overrides array. If this is not
  1999. // done, the array can contain other empty arrays (e.g. `[[], []]`) which leak into the
  2000. // providers array and contaminate any error messages that might be generated.
  2001. return flatten(flatten(providers, (/**
  2002. * @param {?} provider
  2003. * @return {?}
  2004. */
  2005. (provider) => this.getSingleProviderOverrides(provider) || [])));
  2006. }
  2007. /**
  2008. * @private
  2009. * @param {?=} providers
  2010. * @return {?}
  2011. */
  2012. getOverriddenProviders(providers) {
  2013. if (!providers || !providers.length || this.providerOverridesByToken.size === 0)
  2014. return [];
  2015. /** @type {?} */
  2016. const overrides = this.getProviderOverrides(providers);
  2017. /** @type {?} */
  2018. const hasMultiProviderOverrides = overrides.some(isMultiProvider);
  2019. /** @type {?} */
  2020. const overriddenProviders = [...providers, ...overrides];
  2021. // No additional processing is required in case we have no multi providers to override
  2022. if (!hasMultiProviderOverrides) {
  2023. return overriddenProviders;
  2024. }
  2025. /** @type {?} */
  2026. const final = [];
  2027. /** @type {?} */
  2028. const seenMultiProviders = new Set();
  2029. // We iterate through the list of providers in reverse order to make sure multi provider
  2030. // overrides take precedence over the values defined in provider list. We also fiter out all
  2031. // multi providers that have overrides, keeping overridden values only.
  2032. forEachRight(overriddenProviders, (/**
  2033. * @param {?} provider
  2034. * @return {?}
  2035. */
  2036. (provider) => {
  2037. /** @type {?} */
  2038. const token = getProviderToken(provider);
  2039. if (isMultiProvider(provider) && this.providerOverridesByToken.has(token)) {
  2040. if (!seenMultiProviders.has(token)) {
  2041. seenMultiProviders.add(token);
  2042. if (provider && provider.useValue && Array.isArray(provider.useValue)) {
  2043. forEachRight(provider.useValue, (/**
  2044. * @param {?} value
  2045. * @return {?}
  2046. */
  2047. (value) => {
  2048. // Unwrap provider override array into individual providers in final set.
  2049. final.unshift({ provide: token, useValue: value, multi: true });
  2050. }));
  2051. }
  2052. else {
  2053. final.unshift(provider);
  2054. }
  2055. }
  2056. }
  2057. else {
  2058. final.unshift(provider);
  2059. }
  2060. }));
  2061. return final;
  2062. }
  2063. /**
  2064. * @private
  2065. * @param {?=} providers
  2066. * @return {?}
  2067. */
  2068. hasProviderOverrides(providers) {
  2069. return this.getProviderOverrides(providers).length > 0;
  2070. }
  2071. /**
  2072. * @private
  2073. * @param {?} declaration
  2074. * @param {?} field
  2075. * @return {?}
  2076. */
  2077. patchDefWithProviderOverrides(declaration, field) {
  2078. /** @type {?} */
  2079. const def = ((/** @type {?} */ (declaration)))[field];
  2080. if (def && def.providersResolver) {
  2081. this.maybeStoreNgDef(field, declaration);
  2082. /** @type {?} */
  2083. const resolver = def.providersResolver;
  2084. /** @type {?} */
  2085. const processProvidersFn = (/**
  2086. * @param {?} providers
  2087. * @return {?}
  2088. */
  2089. (providers) => this.getOverriddenProviders(providers));
  2090. this.storeFieldOfDefOnType(declaration, field, 'providersResolver');
  2091. def.providersResolver = (/**
  2092. * @param {?} ngDef
  2093. * @return {?}
  2094. */
  2095. (ngDef) => resolver(ngDef, processProvidersFn));
  2096. }
  2097. }
  2098. }
  2099. /**
  2100. * @return {?}
  2101. */
  2102. function initResolvers() {
  2103. return {
  2104. module: new NgModuleResolver(),
  2105. component: new ComponentResolver(),
  2106. directive: new DirectiveResolver(),
  2107. pipe: new PipeResolver()
  2108. };
  2109. }
  2110. /**
  2111. * @template T
  2112. * @param {?} value
  2113. * @return {?}
  2114. */
  2115. function hasNgModuleDef(value) {
  2116. return value.hasOwnProperty('ngModuleDef');
  2117. }
  2118. /**
  2119. * @template T
  2120. * @param {?} maybeFn
  2121. * @return {?}
  2122. */
  2123. function maybeUnwrapFn(maybeFn) {
  2124. return maybeFn instanceof Function ? maybeFn() : maybeFn;
  2125. }
  2126. /**
  2127. * @template T
  2128. * @param {?} values
  2129. * @param {?=} mapFn
  2130. * @return {?}
  2131. */
  2132. function flatten(values, mapFn) {
  2133. /** @type {?} */
  2134. const out = [];
  2135. values.forEach((/**
  2136. * @param {?} value
  2137. * @return {?}
  2138. */
  2139. value => {
  2140. if (Array.isArray(value)) {
  2141. out.push(...flatten(value, mapFn));
  2142. }
  2143. else {
  2144. out.push(mapFn ? mapFn(value) : value);
  2145. }
  2146. }));
  2147. return out;
  2148. }
  2149. /**
  2150. * @param {?} provider
  2151. * @param {?} field
  2152. * @return {?}
  2153. */
  2154. function getProviderField(provider, field) {
  2155. return provider && typeof provider === 'object' && ((/** @type {?} */ (provider)))[field];
  2156. }
  2157. /**
  2158. * @param {?} provider
  2159. * @return {?}
  2160. */
  2161. function getProviderToken(provider) {
  2162. return getProviderField(provider, 'provide') || provider;
  2163. }
  2164. /**
  2165. * @param {?} provider
  2166. * @return {?}
  2167. */
  2168. function isMultiProvider(provider) {
  2169. return !!getProviderField(provider, 'multi');
  2170. }
  2171. /**
  2172. * @template T
  2173. * @param {?} values
  2174. * @param {?} fn
  2175. * @return {?}
  2176. */
  2177. function forEachRight(values, fn) {
  2178. for (let idx = values.length - 1; idx >= 0; idx--) {
  2179. fn(values[idx], idx);
  2180. }
  2181. }
  2182. class R3TestCompiler {
  2183. /**
  2184. * @param {?} testBed
  2185. */
  2186. constructor(testBed) {
  2187. this.testBed = testBed;
  2188. }
  2189. /**
  2190. * @template T
  2191. * @param {?} moduleType
  2192. * @return {?}
  2193. */
  2194. compileModuleSync(moduleType) {
  2195. this.testBed._compileNgModuleSync(moduleType);
  2196. return new ɵNgModuleFactory(moduleType);
  2197. }
  2198. /**
  2199. * @template T
  2200. * @param {?} moduleType
  2201. * @return {?}
  2202. */
  2203. compileModuleAsync(moduleType) {
  2204. return __awaiter(this, void 0, void 0, function* () {
  2205. yield this.testBed._compileNgModuleAsync(moduleType);
  2206. return new ɵNgModuleFactory(moduleType);
  2207. });
  2208. }
  2209. /**
  2210. * @template T
  2211. * @param {?} moduleType
  2212. * @return {?}
  2213. */
  2214. compileModuleAndAllComponentsSync(moduleType) {
  2215. /** @type {?} */
  2216. const ngModuleFactory = this.compileModuleSync(moduleType);
  2217. /** @type {?} */
  2218. const componentFactories = this.testBed._getComponentFactories((/** @type {?} */ (moduleType)));
  2219. return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
  2220. }
  2221. /**
  2222. * @template T
  2223. * @param {?} moduleType
  2224. * @return {?}
  2225. */
  2226. compileModuleAndAllComponentsAsync(moduleType) {
  2227. return __awaiter(this, void 0, void 0, function* () {
  2228. /** @type {?} */
  2229. const ngModuleFactory = yield this.compileModuleAsync(moduleType);
  2230. /** @type {?} */
  2231. const componentFactories = this.testBed._getComponentFactories((/** @type {?} */ (moduleType)));
  2232. return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
  2233. });
  2234. }
  2235. /**
  2236. * @return {?}
  2237. */
  2238. clearCache() { }
  2239. /**
  2240. * @param {?} type
  2241. * @return {?}
  2242. */
  2243. clearCacheFor(type) { }
  2244. /**
  2245. * @param {?} moduleType
  2246. * @return {?}
  2247. */
  2248. getModuleId(moduleType) {
  2249. /** @type {?} */
  2250. const meta = this.testBed._getModuleResolver().resolve(moduleType);
  2251. return meta && meta.id || undefined;
  2252. }
  2253. }
  2254. /**
  2255. * @fileoverview added by tsickle
  2256. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2257. */
  2258. /** @type {?} */
  2259. let _nextRootElementId = 0;
  2260. /** @type {?} */
  2261. const UNDEFINED = Symbol('UNDEFINED');
  2262. /**
  2263. * \@description
  2264. * Configures and initializes environment for unit testing and provides methods for
  2265. * creating components and services in unit tests.
  2266. *
  2267. * TestBed is the primary api for writing unit tests for Angular applications and libraries.
  2268. *
  2269. * Note: Use `TestBed` in tests. It will be set to either `TestBedViewEngine` or `TestBedRender3`
  2270. * according to the compiler used.
  2271. */
  2272. class TestBedRender3 {
  2273. constructor() {
  2274. // Properties
  2275. this.platform = (/** @type {?} */ (null));
  2276. this.ngModule = (/** @type {?} */ (null));
  2277. this._compiler = null;
  2278. this._testModuleRef = null;
  2279. this._activeFixtures = [];
  2280. this._globalCompilationChecked = false;
  2281. }
  2282. /**
  2283. * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
  2284. * angular module. These are common to every test in the suite.
  2285. *
  2286. * This may only be called once, to set up the common providers for the current test
  2287. * suite on the current platform. If you absolutely need to change the providers,
  2288. * first use `resetTestEnvironment`.
  2289. *
  2290. * Test modules and platforms for individual platforms are available from
  2291. * '\@angular/<platform_name>/testing'.
  2292. *
  2293. * \@publicApi
  2294. * @param {?} ngModule
  2295. * @param {?} platform
  2296. * @param {?=} aotSummaries
  2297. * @return {?}
  2298. */
  2299. static initTestEnvironment(ngModule, platform, aotSummaries) {
  2300. /** @type {?} */
  2301. const testBed = _getTestBedRender3();
  2302. testBed.initTestEnvironment(ngModule, platform, aotSummaries);
  2303. return testBed;
  2304. }
  2305. /**
  2306. * Reset the providers for the test injector.
  2307. *
  2308. * \@publicApi
  2309. * @return {?}
  2310. */
  2311. static resetTestEnvironment() { _getTestBedRender3().resetTestEnvironment(); }
  2312. /**
  2313. * @param {?} config
  2314. * @return {?}
  2315. */
  2316. static configureCompiler(config) {
  2317. _getTestBedRender3().configureCompiler(config);
  2318. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2319. }
  2320. /**
  2321. * Allows overriding default providers, directives, pipes, modules of the test injector,
  2322. * which are defined in test_injector.js
  2323. * @param {?} moduleDef
  2324. * @return {?}
  2325. */
  2326. static configureTestingModule(moduleDef) {
  2327. _getTestBedRender3().configureTestingModule(moduleDef);
  2328. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2329. }
  2330. /**
  2331. * Compile components with a `templateUrl` for the test's NgModule.
  2332. * It is necessary to call this function
  2333. * as fetching urls is asynchronous.
  2334. * @return {?}
  2335. */
  2336. static compileComponents() { return _getTestBedRender3().compileComponents(); }
  2337. /**
  2338. * @param {?} ngModule
  2339. * @param {?} override
  2340. * @return {?}
  2341. */
  2342. static overrideModule(ngModule, override) {
  2343. _getTestBedRender3().overrideModule(ngModule, override);
  2344. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2345. }
  2346. /**
  2347. * @param {?} component
  2348. * @param {?} override
  2349. * @return {?}
  2350. */
  2351. static overrideComponent(component, override) {
  2352. _getTestBedRender3().overrideComponent(component, override);
  2353. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2354. }
  2355. /**
  2356. * @param {?} directive
  2357. * @param {?} override
  2358. * @return {?}
  2359. */
  2360. static overrideDirective(directive, override) {
  2361. _getTestBedRender3().overrideDirective(directive, override);
  2362. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2363. }
  2364. /**
  2365. * @param {?} pipe
  2366. * @param {?} override
  2367. * @return {?}
  2368. */
  2369. static overridePipe(pipe, override) {
  2370. _getTestBedRender3().overridePipe(pipe, override);
  2371. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2372. }
  2373. /**
  2374. * @param {?} component
  2375. * @param {?} template
  2376. * @return {?}
  2377. */
  2378. static overrideTemplate(component, template) {
  2379. _getTestBedRender3().overrideComponent(component, { set: { template, templateUrl: (/** @type {?} */ (null)) } });
  2380. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2381. }
  2382. /**
  2383. * Overrides the template of the given component, compiling the template
  2384. * in the context of the TestingModule.
  2385. *
  2386. * Note: This works for JIT and AOTed components as well.
  2387. * @param {?} component
  2388. * @param {?} template
  2389. * @return {?}
  2390. */
  2391. static overrideTemplateUsingTestingModule(component, template) {
  2392. _getTestBedRender3().overrideTemplateUsingTestingModule(component, template);
  2393. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2394. }
  2395. /**
  2396. * @param {?} token
  2397. * @param {?} provider
  2398. * @return {?}
  2399. */
  2400. static overrideProvider(token, provider) {
  2401. _getTestBedRender3().overrideProvider(token, provider);
  2402. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2403. }
  2404. /**
  2405. * @param {?} token
  2406. * @param {?=} notFoundValue
  2407. * @param {?=} flags
  2408. * @return {?}
  2409. */
  2410. static get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
  2411. return _getTestBedRender3().get(token, notFoundValue);
  2412. }
  2413. /**
  2414. * @template T
  2415. * @param {?} component
  2416. * @return {?}
  2417. */
  2418. static createComponent(component) {
  2419. return _getTestBedRender3().createComponent(component);
  2420. }
  2421. /**
  2422. * @return {?}
  2423. */
  2424. static resetTestingModule() {
  2425. _getTestBedRender3().resetTestingModule();
  2426. return (/** @type {?} */ ((/** @type {?} */ (TestBedRender3))));
  2427. }
  2428. /**
  2429. * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
  2430. * angular module. These are common to every test in the suite.
  2431. *
  2432. * This may only be called once, to set up the common providers for the current test
  2433. * suite on the current platform. If you absolutely need to change the providers,
  2434. * first use `resetTestEnvironment`.
  2435. *
  2436. * Test modules and platforms for individual platforms are available from
  2437. * '\@angular/<platform_name>/testing'.
  2438. *
  2439. * \@publicApi
  2440. * @param {?} ngModule
  2441. * @param {?} platform
  2442. * @param {?=} aotSummaries
  2443. * @return {?}
  2444. */
  2445. initTestEnvironment(ngModule, platform, aotSummaries) {
  2446. if (this.platform || this.ngModule) {
  2447. throw new Error('Cannot set base providers because it has already been called');
  2448. }
  2449. this.platform = platform;
  2450. this.ngModule = ngModule;
  2451. this._compiler = new R3TestBedCompiler(this.platform, this.ngModule);
  2452. }
  2453. /**
  2454. * Reset the providers for the test injector.
  2455. *
  2456. * \@publicApi
  2457. * @return {?}
  2458. */
  2459. resetTestEnvironment() {
  2460. this.resetTestingModule();
  2461. this._compiler = null;
  2462. this.platform = (/** @type {?} */ (null));
  2463. this.ngModule = (/** @type {?} */ (null));
  2464. }
  2465. /**
  2466. * @return {?}
  2467. */
  2468. resetTestingModule() {
  2469. this.checkGlobalCompilationFinished();
  2470. ɵresetCompiledComponents();
  2471. if (this._compiler !== null) {
  2472. this.compiler.restoreOriginalState();
  2473. }
  2474. this._compiler = new R3TestBedCompiler(this.platform, this.ngModule);
  2475. this._testModuleRef = null;
  2476. this.destroyActiveFixtures();
  2477. }
  2478. /**
  2479. * @param {?} config
  2480. * @return {?}
  2481. */
  2482. configureCompiler(config) {
  2483. if (config.useJit != null) {
  2484. throw new Error('the Render3 compiler JiT mode is not configurable !');
  2485. }
  2486. if (config.providers !== undefined) {
  2487. this.compiler.setCompilerProviders(config.providers);
  2488. }
  2489. }
  2490. /**
  2491. * @param {?} moduleDef
  2492. * @return {?}
  2493. */
  2494. configureTestingModule(moduleDef) {
  2495. this.assertNotInstantiated('R3TestBed.configureTestingModule', 'configure the test module');
  2496. this.compiler.configureTestingModule(moduleDef);
  2497. }
  2498. /**
  2499. * @return {?}
  2500. */
  2501. compileComponents() { return this.compiler.compileComponents(); }
  2502. /**
  2503. * @param {?} token
  2504. * @param {?=} notFoundValue
  2505. * @param {?=} flags
  2506. * @return {?}
  2507. */
  2508. get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
  2509. if (token === TestBedRender3) {
  2510. return this;
  2511. }
  2512. /** @type {?} */
  2513. const result = this.testModuleRef.injector.get(token, UNDEFINED, flags);
  2514. return result === UNDEFINED ? this.compiler.injector.get(token, notFoundValue, flags) : result;
  2515. }
  2516. /**
  2517. * @param {?} tokens
  2518. * @param {?} fn
  2519. * @param {?=} context
  2520. * @return {?}
  2521. */
  2522. execute(tokens, fn, context) {
  2523. /** @type {?} */
  2524. const params = tokens.map((/**
  2525. * @param {?} t
  2526. * @return {?}
  2527. */
  2528. t => this.get(t)));
  2529. return fn.apply(context, params);
  2530. }
  2531. /**
  2532. * @param {?} ngModule
  2533. * @param {?} override
  2534. * @return {?}
  2535. */
  2536. overrideModule(ngModule, override) {
  2537. this.assertNotInstantiated('overrideModule', 'override module metadata');
  2538. this.compiler.overrideModule(ngModule, override);
  2539. }
  2540. /**
  2541. * @param {?} component
  2542. * @param {?} override
  2543. * @return {?}
  2544. */
  2545. overrideComponent(component, override) {
  2546. this.assertNotInstantiated('overrideComponent', 'override component metadata');
  2547. this.compiler.overrideComponent(component, override);
  2548. }
  2549. /**
  2550. * @param {?} component
  2551. * @param {?} template
  2552. * @return {?}
  2553. */
  2554. overrideTemplateUsingTestingModule(component, template) {
  2555. this.assertNotInstantiated('R3TestBed.overrideTemplateUsingTestingModule', 'Cannot override template when the test module has already been instantiated');
  2556. this.compiler.overrideTemplateUsingTestingModule(component, template);
  2557. }
  2558. /**
  2559. * @param {?} directive
  2560. * @param {?} override
  2561. * @return {?}
  2562. */
  2563. overrideDirective(directive, override) {
  2564. this.assertNotInstantiated('overrideDirective', 'override directive metadata');
  2565. this.compiler.overrideDirective(directive, override);
  2566. }
  2567. /**
  2568. * @param {?} pipe
  2569. * @param {?} override
  2570. * @return {?}
  2571. */
  2572. overridePipe(pipe, override) {
  2573. this.assertNotInstantiated('overridePipe', 'override pipe metadata');
  2574. this.compiler.overridePipe(pipe, override);
  2575. }
  2576. /**
  2577. * Overwrites all providers for the given token with the given provider definition.
  2578. * @param {?} token
  2579. * @param {?} provider
  2580. * @return {?}
  2581. */
  2582. overrideProvider(token, provider) {
  2583. this.compiler.overrideProvider(token, provider);
  2584. }
  2585. /**
  2586. * @template T
  2587. * @param {?} type
  2588. * @return {?}
  2589. */
  2590. createComponent(type) {
  2591. /** @type {?} */
  2592. const testComponentRenderer = this.get(TestComponentRenderer);
  2593. /** @type {?} */
  2594. const rootElId = `root-ng-internal-isolated-${_nextRootElementId++}`;
  2595. testComponentRenderer.insertRootElement(rootElId);
  2596. /** @nocollapse @type {?} */
  2597. const componentDef = ((/** @type {?} */ (type))).ngComponentDef;
  2598. if (!componentDef) {
  2599. throw new Error(`It looks like '${ɵstringify(type)}' has not been IVY compiled - it has no 'ngComponentDef' field`);
  2600. }
  2601. // TODO: Don't cast as `any`, proper type is boolean[]
  2602. /** @type {?} */
  2603. const noNgZone = this.get((/** @type {?} */ (ComponentFixtureNoNgZone)), false);
  2604. // TODO: Don't cast as `any`, proper type is boolean[]
  2605. /** @type {?} */
  2606. const autoDetect = this.get((/** @type {?} */ (ComponentFixtureAutoDetect)), false);
  2607. /** @type {?} */
  2608. const ngZone = noNgZone ? null : this.get((/** @type {?} */ (NgZone)), null);
  2609. /** @type {?} */
  2610. const componentFactory = new ɵRender3ComponentFactory(componentDef);
  2611. /** @type {?} */
  2612. const initComponent = (/**
  2613. * @return {?}
  2614. */
  2615. () => {
  2616. /** @type {?} */
  2617. const componentRef = componentFactory.create(Injector.NULL, [], `#${rootElId}`, this.testModuleRef);
  2618. return new ComponentFixture(componentRef, ngZone, autoDetect);
  2619. });
  2620. /** @type {?} */
  2621. const fixture = ngZone ? ngZone.run(initComponent) : initComponent();
  2622. this._activeFixtures.push(fixture);
  2623. return fixture;
  2624. }
  2625. /**
  2626. * @private
  2627. * @return {?}
  2628. */
  2629. get compiler() {
  2630. if (this._compiler === null) {
  2631. throw new Error(`Need to call TestBed.initTestEnvironment() first`);
  2632. }
  2633. return this._compiler;
  2634. }
  2635. /**
  2636. * @private
  2637. * @return {?}
  2638. */
  2639. get testModuleRef() {
  2640. if (this._testModuleRef === null) {
  2641. this._testModuleRef = this.compiler.finalize();
  2642. }
  2643. return this._testModuleRef;
  2644. }
  2645. /**
  2646. * @private
  2647. * @param {?} methodName
  2648. * @param {?} methodDescription
  2649. * @return {?}
  2650. */
  2651. assertNotInstantiated(methodName, methodDescription) {
  2652. if (this._testModuleRef !== null) {
  2653. throw new Error(`Cannot ${methodDescription} when the test module has already been instantiated. ` +
  2654. `Make sure you are not using \`inject\` before \`${methodName}\`.`);
  2655. }
  2656. }
  2657. /**
  2658. * Check whether the module scoping queue should be flushed, and flush it if needed.
  2659. *
  2660. * When the TestBed is reset, it clears the JIT module compilation queue, cancelling any
  2661. * in-progress module compilation. This creates a potential hazard - the very first time the
  2662. * TestBed is initialized (or if it's reset without being initialized), there may be pending
  2663. * compilations of modules declared in global scope. These compilations should be finished.
  2664. *
  2665. * To ensure that globally declared modules have their components scoped properly, this function
  2666. * is called whenever TestBed is initialized or reset. The _first_ time that this happens, prior
  2667. * to any other operations, the scoping queue is flushed.
  2668. * @private
  2669. * @return {?}
  2670. */
  2671. checkGlobalCompilationFinished() {
  2672. // Checking _testNgModuleRef is null should not be necessary, but is left in as an additional
  2673. // guard that compilations queued in tests (after instantiation) are never flushed accidentally.
  2674. if (!this._globalCompilationChecked && this._testModuleRef === null) {
  2675. ɵflushModuleScopingQueueAsMuchAsPossible();
  2676. }
  2677. this._globalCompilationChecked = true;
  2678. }
  2679. /**
  2680. * @private
  2681. * @return {?}
  2682. */
  2683. destroyActiveFixtures() {
  2684. this._activeFixtures.forEach((/**
  2685. * @param {?} fixture
  2686. * @return {?}
  2687. */
  2688. (fixture) => {
  2689. try {
  2690. fixture.destroy();
  2691. }
  2692. catch (e) {
  2693. console.error('Error during cleanup of component', {
  2694. component: fixture.componentInstance,
  2695. stacktrace: e,
  2696. });
  2697. }
  2698. }));
  2699. this._activeFixtures = [];
  2700. }
  2701. }
  2702. /** @type {?} */
  2703. let testBed;
  2704. /**
  2705. * @return {?}
  2706. */
  2707. function _getTestBedRender3() {
  2708. return testBed = testBed || new TestBedRender3();
  2709. }
  2710. /**
  2711. * @fileoverview added by tsickle
  2712. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2713. */
  2714. /**
  2715. * @return {?}
  2716. */
  2717. function unimplemented() {
  2718. throw Error('unimplemented');
  2719. }
  2720. /**
  2721. * Special interface to the compiler only used by testing
  2722. *
  2723. * \@publicApi
  2724. */
  2725. class TestingCompiler extends Compiler {
  2726. /**
  2727. * @return {?}
  2728. */
  2729. get injector() { throw unimplemented(); }
  2730. /**
  2731. * @param {?} module
  2732. * @param {?} overrides
  2733. * @return {?}
  2734. */
  2735. overrideModule(module, overrides) {
  2736. throw unimplemented();
  2737. }
  2738. /**
  2739. * @param {?} directive
  2740. * @param {?} overrides
  2741. * @return {?}
  2742. */
  2743. overrideDirective(directive, overrides) {
  2744. throw unimplemented();
  2745. }
  2746. /**
  2747. * @param {?} component
  2748. * @param {?} overrides
  2749. * @return {?}
  2750. */
  2751. overrideComponent(component, overrides) {
  2752. throw unimplemented();
  2753. }
  2754. /**
  2755. * @param {?} directive
  2756. * @param {?} overrides
  2757. * @return {?}
  2758. */
  2759. overridePipe(directive, overrides) {
  2760. throw unimplemented();
  2761. }
  2762. /**
  2763. * Allows to pass the compile summary from AOT compilation to the JIT compiler,
  2764. * so that it can use the code generated by AOT.
  2765. * @param {?} summaries
  2766. * @return {?}
  2767. */
  2768. loadAotSummaries(summaries) { throw unimplemented(); }
  2769. /**
  2770. * Gets the component factory for the given component.
  2771. * This assumes that the component has been compiled before calling this call using
  2772. * `compileModuleAndAllComponents*`.
  2773. * @template T
  2774. * @param {?} component
  2775. * @return {?}
  2776. */
  2777. getComponentFactory(component) { throw unimplemented(); }
  2778. /**
  2779. * Returns the component type that is stored in the given error.
  2780. * This can be used for errors created by compileModule...
  2781. * @param {?} error
  2782. * @return {?}
  2783. */
  2784. getComponentFromError(error) { throw unimplemented(); }
  2785. }
  2786. TestingCompiler.decorators = [
  2787. { type: Injectable }
  2788. ];
  2789. /**
  2790. * A factory for creating a Compiler
  2791. *
  2792. * \@publicApi
  2793. * @abstract
  2794. */
  2795. class TestingCompilerFactory {
  2796. }
  2797. /**
  2798. * @fileoverview added by tsickle
  2799. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2800. */
  2801. /** @type {?} */
  2802. const UNDEFINED$1 = new Object();
  2803. /** @type {?} */
  2804. let _nextRootElementId$1 = 0;
  2805. // WARNING: interface has both a type and a value, skipping emit
  2806. /**
  2807. * \@description
  2808. * Configures and initializes environment for unit testing and provides methods for
  2809. * creating components and services in unit tests.
  2810. *
  2811. * `TestBed` is the primary api for writing unit tests for Angular applications and libraries.
  2812. *
  2813. * Note: Use `TestBed` in tests. It will be set to either `TestBedViewEngine` or `TestBedRender3`
  2814. * according to the compiler used.
  2815. */
  2816. class TestBedViewEngine {
  2817. constructor() {
  2818. this._instantiated = false;
  2819. this._compiler = (/** @type {?} */ (null));
  2820. this._moduleRef = (/** @type {?} */ (null));
  2821. this._moduleFactory = (/** @type {?} */ (null));
  2822. this._compilerOptions = [];
  2823. this._moduleOverrides = [];
  2824. this._componentOverrides = [];
  2825. this._directiveOverrides = [];
  2826. this._pipeOverrides = [];
  2827. this._providers = [];
  2828. this._declarations = [];
  2829. this._imports = [];
  2830. this._schemas = [];
  2831. this._activeFixtures = [];
  2832. this._testEnvAotSummaries = (/**
  2833. * @return {?}
  2834. */
  2835. () => []);
  2836. this._aotSummaries = [];
  2837. this._templateOverrides = [];
  2838. this._isRoot = true;
  2839. this._rootProviderOverrides = [];
  2840. this.platform = (/** @type {?} */ (null));
  2841. this.ngModule = (/** @type {?} */ (null));
  2842. }
  2843. /**
  2844. * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
  2845. * angular module. These are common to every test in the suite.
  2846. *
  2847. * This may only be called once, to set up the common providers for the current test
  2848. * suite on the current platform. If you absolutely need to change the providers,
  2849. * first use `resetTestEnvironment`.
  2850. *
  2851. * Test modules and platforms for individual platforms are available from
  2852. * '\@angular/<platform_name>/testing'.
  2853. * @param {?} ngModule
  2854. * @param {?} platform
  2855. * @param {?=} aotSummaries
  2856. * @return {?}
  2857. */
  2858. static initTestEnvironment(ngModule, platform, aotSummaries) {
  2859. /** @type {?} */
  2860. const testBed = _getTestBedViewEngine();
  2861. testBed.initTestEnvironment(ngModule, platform, aotSummaries);
  2862. return testBed;
  2863. }
  2864. /**
  2865. * Reset the providers for the test injector.
  2866. * @return {?}
  2867. */
  2868. static resetTestEnvironment() { _getTestBedViewEngine().resetTestEnvironment(); }
  2869. /**
  2870. * @return {?}
  2871. */
  2872. static resetTestingModule() {
  2873. _getTestBedViewEngine().resetTestingModule();
  2874. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2875. }
  2876. /**
  2877. * Allows overriding default compiler providers and settings
  2878. * which are defined in test_injector.js
  2879. * @param {?} config
  2880. * @return {?}
  2881. */
  2882. static configureCompiler(config) {
  2883. _getTestBedViewEngine().configureCompiler(config);
  2884. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2885. }
  2886. /**
  2887. * Allows overriding default providers, directives, pipes, modules of the test injector,
  2888. * which are defined in test_injector.js
  2889. * @param {?} moduleDef
  2890. * @return {?}
  2891. */
  2892. static configureTestingModule(moduleDef) {
  2893. _getTestBedViewEngine().configureTestingModule(moduleDef);
  2894. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2895. }
  2896. /**
  2897. * Compile components with a `templateUrl` for the test's NgModule.
  2898. * It is necessary to call this function
  2899. * as fetching urls is asynchronous.
  2900. * @return {?}
  2901. */
  2902. static compileComponents() { return getTestBed().compileComponents(); }
  2903. /**
  2904. * @param {?} ngModule
  2905. * @param {?} override
  2906. * @return {?}
  2907. */
  2908. static overrideModule(ngModule, override) {
  2909. _getTestBedViewEngine().overrideModule(ngModule, override);
  2910. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2911. }
  2912. /**
  2913. * @param {?} component
  2914. * @param {?} override
  2915. * @return {?}
  2916. */
  2917. static overrideComponent(component, override) {
  2918. _getTestBedViewEngine().overrideComponent(component, override);
  2919. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2920. }
  2921. /**
  2922. * @param {?} directive
  2923. * @param {?} override
  2924. * @return {?}
  2925. */
  2926. static overrideDirective(directive, override) {
  2927. _getTestBedViewEngine().overrideDirective(directive, override);
  2928. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2929. }
  2930. /**
  2931. * @param {?} pipe
  2932. * @param {?} override
  2933. * @return {?}
  2934. */
  2935. static overridePipe(pipe, override) {
  2936. _getTestBedViewEngine().overridePipe(pipe, override);
  2937. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2938. }
  2939. /**
  2940. * @param {?} component
  2941. * @param {?} template
  2942. * @return {?}
  2943. */
  2944. static overrideTemplate(component, template) {
  2945. _getTestBedViewEngine().overrideComponent(component, { set: { template, templateUrl: (/** @type {?} */ (null)) } });
  2946. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2947. }
  2948. /**
  2949. * Overrides the template of the given component, compiling the template
  2950. * in the context of the TestingModule.
  2951. *
  2952. * Note: This works for JIT and AOTed components as well.
  2953. * @param {?} component
  2954. * @param {?} template
  2955. * @return {?}
  2956. */
  2957. static overrideTemplateUsingTestingModule(component, template) {
  2958. _getTestBedViewEngine().overrideTemplateUsingTestingModule(component, template);
  2959. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2960. }
  2961. /**
  2962. * @param {?} token
  2963. * @param {?} provider
  2964. * @return {?}
  2965. */
  2966. static overrideProvider(token, provider) {
  2967. _getTestBedViewEngine().overrideProvider(token, (/** @type {?} */ (provider)));
  2968. return (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  2969. }
  2970. /**
  2971. * @param {?} token
  2972. * @param {?=} notFoundValue
  2973. * @param {?=} flags
  2974. * @return {?}
  2975. */
  2976. static get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
  2977. return _getTestBedViewEngine().get(token, notFoundValue, flags);
  2978. }
  2979. /**
  2980. * @template T
  2981. * @param {?} component
  2982. * @return {?}
  2983. */
  2984. static createComponent(component) {
  2985. return _getTestBedViewEngine().createComponent(component);
  2986. }
  2987. /**
  2988. * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
  2989. * angular module. These are common to every test in the suite.
  2990. *
  2991. * This may only be called once, to set up the common providers for the current test
  2992. * suite on the current platform. If you absolutely need to change the providers,
  2993. * first use `resetTestEnvironment`.
  2994. *
  2995. * Test modules and platforms for individual platforms are available from
  2996. * '\@angular/<platform_name>/testing'.
  2997. * @param {?} ngModule
  2998. * @param {?} platform
  2999. * @param {?=} aotSummaries
  3000. * @return {?}
  3001. */
  3002. initTestEnvironment(ngModule, platform, aotSummaries) {
  3003. if (this.platform || this.ngModule) {
  3004. throw new Error('Cannot set base providers because it has already been called');
  3005. }
  3006. this.platform = platform;
  3007. this.ngModule = ngModule;
  3008. if (aotSummaries) {
  3009. this._testEnvAotSummaries = aotSummaries;
  3010. }
  3011. }
  3012. /**
  3013. * Reset the providers for the test injector.
  3014. * @return {?}
  3015. */
  3016. resetTestEnvironment() {
  3017. this.resetTestingModule();
  3018. this.platform = (/** @type {?} */ (null));
  3019. this.ngModule = (/** @type {?} */ (null));
  3020. this._testEnvAotSummaries = (/**
  3021. * @return {?}
  3022. */
  3023. () => []);
  3024. }
  3025. /**
  3026. * @return {?}
  3027. */
  3028. resetTestingModule() {
  3029. ɵclearOverrides();
  3030. this._aotSummaries = [];
  3031. this._templateOverrides = [];
  3032. this._compiler = (/** @type {?} */ (null));
  3033. this._moduleOverrides = [];
  3034. this._componentOverrides = [];
  3035. this._directiveOverrides = [];
  3036. this._pipeOverrides = [];
  3037. this._isRoot = true;
  3038. this._rootProviderOverrides = [];
  3039. this._moduleRef = (/** @type {?} */ (null));
  3040. this._moduleFactory = (/** @type {?} */ (null));
  3041. this._compilerOptions = [];
  3042. this._providers = [];
  3043. this._declarations = [];
  3044. this._imports = [];
  3045. this._schemas = [];
  3046. this._instantiated = false;
  3047. this._activeFixtures.forEach((/**
  3048. * @param {?} fixture
  3049. * @return {?}
  3050. */
  3051. (fixture) => {
  3052. try {
  3053. fixture.destroy();
  3054. }
  3055. catch (e) {
  3056. console.error('Error during cleanup of component', {
  3057. component: fixture.componentInstance,
  3058. stacktrace: e,
  3059. });
  3060. }
  3061. }));
  3062. this._activeFixtures = [];
  3063. }
  3064. /**
  3065. * @param {?} config
  3066. * @return {?}
  3067. */
  3068. configureCompiler(config) {
  3069. this._assertNotInstantiated('TestBed.configureCompiler', 'configure the compiler');
  3070. this._compilerOptions.push(config);
  3071. }
  3072. /**
  3073. * @param {?} moduleDef
  3074. * @return {?}
  3075. */
  3076. configureTestingModule(moduleDef) {
  3077. this._assertNotInstantiated('TestBed.configureTestingModule', 'configure the test module');
  3078. if (moduleDef.providers) {
  3079. this._providers.push(...moduleDef.providers);
  3080. }
  3081. if (moduleDef.declarations) {
  3082. this._declarations.push(...moduleDef.declarations);
  3083. }
  3084. if (moduleDef.imports) {
  3085. this._imports.push(...moduleDef.imports);
  3086. }
  3087. if (moduleDef.schemas) {
  3088. this._schemas.push(...moduleDef.schemas);
  3089. }
  3090. if (moduleDef.aotSummaries) {
  3091. this._aotSummaries.push(moduleDef.aotSummaries);
  3092. }
  3093. }
  3094. /**
  3095. * @return {?}
  3096. */
  3097. compileComponents() {
  3098. if (this._moduleFactory || this._instantiated) {
  3099. return Promise.resolve(null);
  3100. }
  3101. /** @type {?} */
  3102. const moduleType = this._createCompilerAndModule();
  3103. return this._compiler.compileModuleAndAllComponentsAsync(moduleType)
  3104. .then((/**
  3105. * @param {?} moduleAndComponentFactories
  3106. * @return {?}
  3107. */
  3108. (moduleAndComponentFactories) => {
  3109. this._moduleFactory = moduleAndComponentFactories.ngModuleFactory;
  3110. }));
  3111. }
  3112. /**
  3113. * @private
  3114. * @return {?}
  3115. */
  3116. _initIfNeeded() {
  3117. if (this._instantiated) {
  3118. return;
  3119. }
  3120. if (!this._moduleFactory) {
  3121. try {
  3122. /** @type {?} */
  3123. const moduleType = this._createCompilerAndModule();
  3124. this._moduleFactory =
  3125. this._compiler.compileModuleAndAllComponentsSync(moduleType).ngModuleFactory;
  3126. }
  3127. catch (e) {
  3128. /** @type {?} */
  3129. const errorCompType = this._compiler.getComponentFromError(e);
  3130. if (errorCompType) {
  3131. throw new Error(`This test module uses the component ${ɵstringify(errorCompType)} which is using a "templateUrl" or "styleUrls", but they were never compiled. ` +
  3132. `Please call "TestBed.compileComponents" before your test.`);
  3133. }
  3134. else {
  3135. throw e;
  3136. }
  3137. }
  3138. }
  3139. for (const { component, templateOf } of this._templateOverrides) {
  3140. /** @type {?} */
  3141. const compFactory = this._compiler.getComponentFactory(templateOf);
  3142. ɵoverrideComponentView(component, compFactory);
  3143. }
  3144. /** @type {?} */
  3145. const ngZone = new NgZone({ enableLongStackTrace: true });
  3146. /** @type {?} */
  3147. const providers = [{ provide: NgZone, useValue: ngZone }];
  3148. /** @type {?} */
  3149. const ngZoneInjector = Injector.create({
  3150. providers: providers,
  3151. parent: this.platform.injector,
  3152. name: this._moduleFactory.moduleType.name
  3153. });
  3154. this._moduleRef = this._moduleFactory.create(ngZoneInjector);
  3155. // ApplicationInitStatus.runInitializers() is marked @internal to core. So casting to any
  3156. // before accessing it.
  3157. ((/** @type {?} */ (this._moduleRef.injector.get(ApplicationInitStatus)))).runInitializers();
  3158. this._instantiated = true;
  3159. }
  3160. /**
  3161. * @private
  3162. * @return {?}
  3163. */
  3164. _createCompilerAndModule() {
  3165. /** @type {?} */
  3166. const providers = this._providers.concat([{ provide: TestBed, useValue: this }]);
  3167. /** @type {?} */
  3168. const declarations = [...this._declarations, ...this._templateOverrides.map((/**
  3169. * @param {?} entry
  3170. * @return {?}
  3171. */
  3172. entry => entry.templateOf))];
  3173. /** @type {?} */
  3174. const rootScopeImports = [];
  3175. /** @type {?} */
  3176. const rootProviderOverrides = this._rootProviderOverrides;
  3177. if (this._isRoot) {
  3178. class RootScopeModule {
  3179. }
  3180. RootScopeModule.decorators = [
  3181. { type: NgModule, args: [{
  3182. providers: [
  3183. ...rootProviderOverrides,
  3184. ],
  3185. jit: true,
  3186. },] },
  3187. ];
  3188. rootScopeImports.push(RootScopeModule);
  3189. }
  3190. providers.push({ provide: ɵAPP_ROOT, useValue: this._isRoot });
  3191. /** @type {?} */
  3192. const imports = [rootScopeImports, this.ngModule, this._imports];
  3193. /** @type {?} */
  3194. const schemas = this._schemas;
  3195. class DynamicTestModule {
  3196. }
  3197. DynamicTestModule.decorators = [
  3198. { type: NgModule, args: [{ providers, declarations, imports, schemas, jit: true },] },
  3199. ];
  3200. /** @type {?} */
  3201. const compilerFactory = this.platform.injector.get(TestingCompilerFactory);
  3202. this._compiler = compilerFactory.createTestingCompiler(this._compilerOptions);
  3203. for (const summary of [this._testEnvAotSummaries, ...this._aotSummaries]) {
  3204. this._compiler.loadAotSummaries(summary);
  3205. }
  3206. this._moduleOverrides.forEach((/**
  3207. * @param {?} entry
  3208. * @return {?}
  3209. */
  3210. (entry) => this._compiler.overrideModule(entry[0], entry[1])));
  3211. this._componentOverrides.forEach((/**
  3212. * @param {?} entry
  3213. * @return {?}
  3214. */
  3215. (entry) => this._compiler.overrideComponent(entry[0], entry[1])));
  3216. this._directiveOverrides.forEach((/**
  3217. * @param {?} entry
  3218. * @return {?}
  3219. */
  3220. (entry) => this._compiler.overrideDirective(entry[0], entry[1])));
  3221. this._pipeOverrides.forEach((/**
  3222. * @param {?} entry
  3223. * @return {?}
  3224. */
  3225. (entry) => this._compiler.overridePipe(entry[0], entry[1])));
  3226. return DynamicTestModule;
  3227. }
  3228. /**
  3229. * @private
  3230. * @param {?} methodName
  3231. * @param {?} methodDescription
  3232. * @return {?}
  3233. */
  3234. _assertNotInstantiated(methodName, methodDescription) {
  3235. if (this._instantiated) {
  3236. throw new Error(`Cannot ${methodDescription} when the test module has already been instantiated. ` +
  3237. `Make sure you are not using \`inject\` before \`${methodName}\`.`);
  3238. }
  3239. }
  3240. /**
  3241. * @param {?} token
  3242. * @param {?=} notFoundValue
  3243. * @param {?=} flags
  3244. * @return {?}
  3245. */
  3246. get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
  3247. this._initIfNeeded();
  3248. if (token === TestBed) {
  3249. return this;
  3250. }
  3251. // Tests can inject things from the ng module and from the compiler,
  3252. // but the ng module can't inject things from the compiler and vice versa.
  3253. /** @type {?} */
  3254. const result = this._moduleRef.injector.get(token, UNDEFINED$1, flags);
  3255. return result === UNDEFINED$1 ? this._compiler.injector.get(token, notFoundValue, flags) : result;
  3256. }
  3257. /**
  3258. * @param {?} tokens
  3259. * @param {?} fn
  3260. * @param {?=} context
  3261. * @return {?}
  3262. */
  3263. execute(tokens, fn, context) {
  3264. this._initIfNeeded();
  3265. /** @type {?} */
  3266. const params = tokens.map((/**
  3267. * @param {?} t
  3268. * @return {?}
  3269. */
  3270. t => this.get(t)));
  3271. return fn.apply(context, params);
  3272. }
  3273. /**
  3274. * @param {?} ngModule
  3275. * @param {?} override
  3276. * @return {?}
  3277. */
  3278. overrideModule(ngModule, override) {
  3279. this._assertNotInstantiated('overrideModule', 'override module metadata');
  3280. this._moduleOverrides.push([ngModule, override]);
  3281. }
  3282. /**
  3283. * @param {?} component
  3284. * @param {?} override
  3285. * @return {?}
  3286. */
  3287. overrideComponent(component, override) {
  3288. this._assertNotInstantiated('overrideComponent', 'override component metadata');
  3289. this._componentOverrides.push([component, override]);
  3290. }
  3291. /**
  3292. * @param {?} directive
  3293. * @param {?} override
  3294. * @return {?}
  3295. */
  3296. overrideDirective(directive, override) {
  3297. this._assertNotInstantiated('overrideDirective', 'override directive metadata');
  3298. this._directiveOverrides.push([directive, override]);
  3299. }
  3300. /**
  3301. * @param {?} pipe
  3302. * @param {?} override
  3303. * @return {?}
  3304. */
  3305. overridePipe(pipe, override) {
  3306. this._assertNotInstantiated('overridePipe', 'override pipe metadata');
  3307. this._pipeOverrides.push([pipe, override]);
  3308. }
  3309. /**
  3310. * @param {?} token
  3311. * @param {?} provider
  3312. * @return {?}
  3313. */
  3314. overrideProvider(token, provider) {
  3315. this.overrideProviderImpl(token, provider);
  3316. }
  3317. /**
  3318. * @private
  3319. * @param {?} token
  3320. * @param {?} provider
  3321. * @param {?=} deprecated
  3322. * @return {?}
  3323. */
  3324. overrideProviderImpl(token, provider, deprecated = false) {
  3325. /** @type {?} */
  3326. let def = null;
  3327. if (typeof token !== 'string' && (def = ɵgetInjectableDef(token)) && def.providedIn === 'root') {
  3328. if (provider.useFactory) {
  3329. this._rootProviderOverrides.push({ provide: token, useFactory: provider.useFactory, deps: provider.deps || [] });
  3330. }
  3331. else {
  3332. this._rootProviderOverrides.push({ provide: token, useValue: provider.useValue });
  3333. }
  3334. }
  3335. /** @type {?} */
  3336. let flags = 0;
  3337. /** @type {?} */
  3338. let value;
  3339. if (provider.useFactory) {
  3340. flags |= 1024 /* TypeFactoryProvider */;
  3341. value = provider.useFactory;
  3342. }
  3343. else {
  3344. flags |= 256 /* TypeValueProvider */;
  3345. value = provider.useValue;
  3346. }
  3347. /** @type {?} */
  3348. const deps = (provider.deps || []).map((/**
  3349. * @param {?} dep
  3350. * @return {?}
  3351. */
  3352. (dep) => {
  3353. /** @type {?} */
  3354. let depFlags = 0 /* None */;
  3355. /** @type {?} */
  3356. let depToken;
  3357. if (Array.isArray(dep)) {
  3358. dep.forEach((/**
  3359. * @param {?} entry
  3360. * @return {?}
  3361. */
  3362. (entry) => {
  3363. if (entry instanceof Optional) {
  3364. depFlags |= 2 /* Optional */;
  3365. }
  3366. else if (entry instanceof SkipSelf) {
  3367. depFlags |= 1 /* SkipSelf */;
  3368. }
  3369. else {
  3370. depToken = entry;
  3371. }
  3372. }));
  3373. }
  3374. else {
  3375. depToken = dep;
  3376. }
  3377. return [depFlags, depToken];
  3378. }));
  3379. ɵoverrideProvider({ token, flags, deps, value, deprecatedBehavior: deprecated });
  3380. }
  3381. /**
  3382. * @param {?} component
  3383. * @param {?} template
  3384. * @return {?}
  3385. */
  3386. overrideTemplateUsingTestingModule(component, template) {
  3387. this._assertNotInstantiated('overrideTemplateUsingTestingModule', 'override template');
  3388. class OverrideComponent {
  3389. }
  3390. OverrideComponent.decorators = [
  3391. { type: Component, args: [{ selector: 'empty', template, jit: true },] },
  3392. ];
  3393. this._templateOverrides.push({ component, templateOf: OverrideComponent });
  3394. }
  3395. /**
  3396. * @template T
  3397. * @param {?} component
  3398. * @return {?}
  3399. */
  3400. createComponent(component) {
  3401. this._initIfNeeded();
  3402. /** @type {?} */
  3403. const componentFactory = this._compiler.getComponentFactory(component);
  3404. if (!componentFactory) {
  3405. throw new Error(`Cannot create the component ${ɵstringify(component)} as it was not imported into the testing module!`);
  3406. }
  3407. // TODO: Don't cast as `any`, proper type is boolean[]
  3408. /** @type {?} */
  3409. const noNgZone = this.get((/** @type {?} */ (ComponentFixtureNoNgZone)), false);
  3410. // TODO: Don't cast as `any`, proper type is boolean[]
  3411. /** @type {?} */
  3412. const autoDetect = this.get((/** @type {?} */ (ComponentFixtureAutoDetect)), false);
  3413. /** @type {?} */
  3414. const ngZone = noNgZone ? null : this.get((/** @type {?} */ (NgZone)), null);
  3415. /** @type {?} */
  3416. const testComponentRenderer = this.get(TestComponentRenderer);
  3417. /** @type {?} */
  3418. const rootElId = `root${_nextRootElementId$1++}`;
  3419. testComponentRenderer.insertRootElement(rootElId);
  3420. /** @type {?} */
  3421. const initComponent = (/**
  3422. * @return {?}
  3423. */
  3424. () => {
  3425. /** @type {?} */
  3426. const componentRef = componentFactory.create(Injector.NULL, [], `#${rootElId}`, this._moduleRef);
  3427. return new ComponentFixture(componentRef, ngZone, autoDetect);
  3428. });
  3429. /** @type {?} */
  3430. const fixture = !ngZone ? initComponent() : ngZone.run(initComponent);
  3431. this._activeFixtures.push(fixture);
  3432. return fixture;
  3433. }
  3434. }
  3435. /**
  3436. * \@description
  3437. * Configures and initializes environment for unit testing and provides methods for
  3438. * creating components and services in unit tests.
  3439. *
  3440. * `TestBed` is the primary api for writing unit tests for Angular applications and libraries.
  3441. *
  3442. * Note: Use `TestBed` in tests. It will be set to either `TestBedViewEngine` or `TestBedRender3`
  3443. * according to the compiler used.
  3444. *
  3445. * \@publicApi
  3446. * @type {?}
  3447. */
  3448. const TestBed = ɵivyEnabled ? (/** @type {?} */ ((/** @type {?} */ (TestBedRender3)))) : (/** @type {?} */ ((/** @type {?} */ (TestBedViewEngine))));
  3449. /**
  3450. * Returns a singleton of the applicable `TestBed`.
  3451. *
  3452. * It will be either an instance of `TestBedViewEngine` or `TestBedRender3`.
  3453. *
  3454. * \@publicApi
  3455. * @type {?}
  3456. */
  3457. const getTestBed = ɵivyEnabled ? _getTestBedRender3 : _getTestBedViewEngine;
  3458. /** @type {?} */
  3459. let testBed$1;
  3460. /**
  3461. * @return {?}
  3462. */
  3463. function _getTestBedViewEngine() {
  3464. return testBed$1 = testBed$1 || new TestBedViewEngine();
  3465. }
  3466. /**
  3467. * Allows injecting dependencies in `beforeEach()` and `it()`.
  3468. *
  3469. * Example:
  3470. *
  3471. * ```
  3472. * beforeEach(inject([Dependency, AClass], (dep, object) => {
  3473. * // some code that uses `dep` and `object`
  3474. * // ...
  3475. * }));
  3476. *
  3477. * it('...', inject([AClass], (object) => {
  3478. * object.doSomething();
  3479. * expect(...);
  3480. * })
  3481. * ```
  3482. *
  3483. * Notes:
  3484. * - inject is currently a function because of some Traceur limitation the syntax should
  3485. * eventually
  3486. * becomes `it('...', \@Inject (object: AClass, async: AsyncTestCompleter) => { ... });`
  3487. *
  3488. * \@publicApi
  3489. * @param {?} tokens
  3490. * @param {?} fn
  3491. * @return {?}
  3492. */
  3493. function inject(tokens, fn) {
  3494. /** @type {?} */
  3495. const testBed = getTestBed();
  3496. if (tokens.indexOf(AsyncTestCompleter) >= 0) {
  3497. // Not using an arrow function to preserve context passed from call site
  3498. return (/**
  3499. * @return {?}
  3500. */
  3501. function () {
  3502. // Return an async test method that returns a Promise if AsyncTestCompleter is one of
  3503. // the injected tokens.
  3504. return testBed.compileComponents().then((/**
  3505. * @return {?}
  3506. */
  3507. () => {
  3508. /** @type {?} */
  3509. const completer = testBed.get(AsyncTestCompleter);
  3510. testBed.execute(tokens, fn, this);
  3511. return completer.promise;
  3512. }));
  3513. });
  3514. }
  3515. else {
  3516. // Not using an arrow function to preserve context passed from call site
  3517. return (/**
  3518. * @return {?}
  3519. */
  3520. function () { return testBed.execute(tokens, fn, this); });
  3521. }
  3522. }
  3523. /**
  3524. * \@publicApi
  3525. */
  3526. class InjectSetupWrapper {
  3527. /**
  3528. * @param {?} _moduleDef
  3529. */
  3530. constructor(_moduleDef) {
  3531. this._moduleDef = _moduleDef;
  3532. }
  3533. /**
  3534. * @private
  3535. * @return {?}
  3536. */
  3537. _addModule() {
  3538. /** @type {?} */
  3539. const moduleDef = this._moduleDef();
  3540. if (moduleDef) {
  3541. getTestBed().configureTestingModule(moduleDef);
  3542. }
  3543. }
  3544. /**
  3545. * @param {?} tokens
  3546. * @param {?} fn
  3547. * @return {?}
  3548. */
  3549. inject(tokens, fn) {
  3550. /** @type {?} */
  3551. const self = this;
  3552. // Not using an arrow function to preserve context passed from call site
  3553. return (/**
  3554. * @return {?}
  3555. */
  3556. function () {
  3557. self._addModule();
  3558. return inject(tokens, fn).call(this);
  3559. });
  3560. }
  3561. }
  3562. /**
  3563. * @param {?} moduleDef
  3564. * @param {?=} fn
  3565. * @return {?}
  3566. */
  3567. function withModule(moduleDef, fn) {
  3568. if (fn) {
  3569. // Not using an arrow function to preserve context passed from call site
  3570. return (/**
  3571. * @return {?}
  3572. */
  3573. function () {
  3574. /** @type {?} */
  3575. const testBed = getTestBed();
  3576. if (moduleDef) {
  3577. testBed.configureTestingModule(moduleDef);
  3578. }
  3579. return fn.apply(this);
  3580. });
  3581. }
  3582. return new InjectSetupWrapper((/**
  3583. * @return {?}
  3584. */
  3585. () => moduleDef));
  3586. }
  3587. /**
  3588. * @fileoverview added by tsickle
  3589. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3590. */
  3591. /** @type {?} */
  3592. const _global$1 = (/** @type {?} */ ((typeof window === 'undefined' ? global : window)));
  3593. // Reset the test providers and the fake async zone before each test.
  3594. if (_global$1.beforeEach) {
  3595. _global$1.beforeEach((/**
  3596. * @return {?}
  3597. */
  3598. () => {
  3599. TestBed.resetTestingModule();
  3600. resetFakeAsyncZone();
  3601. }));
  3602. }
  3603. // TODO(juliemr): remove this, only used because we need to export something to have compilation
  3604. // work.
  3605. /** @type {?} */
  3606. const __core_private_testing_placeholder__ = '';
  3607. /**
  3608. * @fileoverview added by tsickle
  3609. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3610. */
  3611. /**
  3612. * @license
  3613. * Copyright Google Inc. All Rights Reserved.
  3614. *
  3615. * Use of this source code is governed by an MIT-style license that can be
  3616. * found in the LICENSE file at https://angular.io/license
  3617. */
  3618. /**
  3619. * @fileoverview added by tsickle
  3620. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3621. */
  3622. /**
  3623. * @fileoverview added by tsickle
  3624. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3625. */
  3626. /**
  3627. * @fileoverview added by tsickle
  3628. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3629. */
  3630. /**
  3631. * @fileoverview added by tsickle
  3632. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3633. */
  3634. /**
  3635. * Generated bundle index. Do not edit.
  3636. */
  3637. export { TestBedRender3 as ɵangular_packages_core_testing_testing_b, _getTestBedRender3 as ɵangular_packages_core_testing_testing_c, TestBedViewEngine as ɵangular_packages_core_testing_testing_a, TestBed, getTestBed, inject, InjectSetupWrapper, withModule, MetadataOverrider as ɵMetadataOverrider, async, ComponentFixture, resetFakeAsyncZone, fakeAsync, tick, flush, discardPeriodicTasks, flushMicrotasks, TestComponentRenderer, ComponentFixtureAutoDetect, ComponentFixtureNoNgZone, __core_private_testing_placeholder__, TestingCompiler as ɵTestingCompiler, TestingCompilerFactory as ɵTestingCompilerFactory };
  3638. //# sourceMappingURL=testing.js.map