123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. /**
  2. * @license Angular v5.2.11
  3. * (c) 2010-2018 Google, Inc. https://angular.io/
  4. * License: MIT
  5. */
  6. import { ApplicationInitStatus, Compiler, Component, Injectable, InjectionToken, Injector, NgModule, NgZone, Optional, RendererFactory2, SkipSelf, getDebugNode, ɵclearOverrides, ɵoverrideComponentView, ɵoverrideProvider, ɵstringify } from '@angular/core';
  7. /**
  8. * @license
  9. * Copyright Google Inc. All Rights Reserved.
  10. *
  11. * Use of this source code is governed by an MIT-style license that can be
  12. * found in the LICENSE file at https://angular.io/license
  13. */
  14. const _global = (typeof window === 'undefined' ? global : window);
  15. /**
  16. * Wraps a test function in an asynchronous test zone. The test will automatically
  17. * complete when all asynchronous calls within this zone are done. Can be used
  18. * to wrap an {@link inject} call.
  19. *
  20. * Example:
  21. *
  22. * ```
  23. * it('...', async(inject([AClass], (object) => {
  24. * object.doSomething.then(() => {
  25. * expect(...);
  26. * })
  27. * });
  28. * ```
  29. *
  30. * @stable
  31. */
  32. function async(fn) {
  33. // If we're running using the Jasmine test framework, adapt to call the 'done'
  34. // function when asynchronous activity is finished.
  35. if (_global.jasmine) {
  36. // Not using an arrow function to preserve context passed from call site
  37. return function (done) {
  38. if (!done) {
  39. // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
  40. // fake it here and assume sync.
  41. done = function () { };
  42. done.fail = function (e) { throw e; };
  43. }
  44. runInTestZone(fn, this, done, (err) => {
  45. if (typeof err === 'string') {
  46. return done.fail(new Error(err));
  47. }
  48. else {
  49. done.fail(err);
  50. }
  51. });
  52. };
  53. }
  54. // Otherwise, return a promise which will resolve when asynchronous activity
  55. // is finished. This will be correctly consumed by the Mocha framework with
  56. // it('...', async(myFn)); or can be used in a custom framework.
  57. // Not using an arrow function to preserve context passed from call site
  58. return function () {
  59. return new Promise((finishCallback, failCallback) => {
  60. runInTestZone(fn, this, finishCallback, failCallback);
  61. });
  62. };
  63. }
  64. function runInTestZone(fn, context, finishCallback, failCallback) {
  65. const currentZone = Zone.current;
  66. const AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
  67. if (AsyncTestZoneSpec === undefined) {
  68. throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
  69. 'Please make sure that your environment includes zone.js/dist/async-test.js');
  70. }
  71. const ProxyZoneSpec = Zone['ProxyZoneSpec'];
  72. if (ProxyZoneSpec === undefined) {
  73. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  74. 'Please make sure that your environment includes zone.js/dist/proxy.js');
  75. }
  76. const proxyZoneSpec = ProxyZoneSpec.get();
  77. ProxyZoneSpec.assertPresent();
  78. // We need to create the AsyncTestZoneSpec outside the ProxyZone.
  79. // If we do it in ProxyZone then we will get to infinite recursion.
  80. const proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
  81. const previousDelegate = proxyZoneSpec.getDelegate();
  82. proxyZone.parent.run(() => {
  83. const testZoneSpec = new AsyncTestZoneSpec(() => {
  84. // Need to restore the original zone.
  85. currentZone.run(() => {
  86. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  87. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  88. proxyZoneSpec.setDelegate(previousDelegate);
  89. }
  90. finishCallback();
  91. });
  92. }, (error) => {
  93. // Need to restore the original zone.
  94. currentZone.run(() => {
  95. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  96. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  97. proxyZoneSpec.setDelegate(previousDelegate);
  98. }
  99. failCallback(error);
  100. });
  101. }, 'test');
  102. proxyZoneSpec.setDelegate(testZoneSpec);
  103. });
  104. return Zone.current.runGuarded(fn, context);
  105. }
  106. /**
  107. * @license
  108. * Copyright Google Inc. All Rights Reserved.
  109. *
  110. * Use of this source code is governed by an MIT-style license that can be
  111. * found in the LICENSE file at https://angular.io/license
  112. */
  113. /**
  114. * Fixture for debugging and testing a component.
  115. *
  116. * @stable
  117. */
  118. class ComponentFixture {
  119. constructor(componentRef, ngZone, _autoDetect) {
  120. this.componentRef = componentRef;
  121. this.ngZone = ngZone;
  122. this._autoDetect = _autoDetect;
  123. this._isStable = true;
  124. this._isDestroyed = false;
  125. this._resolve = null;
  126. this._promise = null;
  127. this._onUnstableSubscription = null;
  128. this._onStableSubscription = null;
  129. this._onMicrotaskEmptySubscription = null;
  130. this._onErrorSubscription = null;
  131. this.changeDetectorRef = componentRef.changeDetectorRef;
  132. this.elementRef = componentRef.location;
  133. this.debugElement = getDebugNode(this.elementRef.nativeElement);
  134. this.componentInstance = componentRef.instance;
  135. this.nativeElement = this.elementRef.nativeElement;
  136. this.componentRef = componentRef;
  137. this.ngZone = ngZone;
  138. if (ngZone) {
  139. // Create subscriptions outside the NgZone so that the callbacks run oustide
  140. // of NgZone.
  141. ngZone.runOutsideAngular(() => {
  142. this._onUnstableSubscription =
  143. ngZone.onUnstable.subscribe({ next: () => { this._isStable = false; } });
  144. this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
  145. next: () => {
  146. if (this._autoDetect) {
  147. // Do a change detection run with checkNoChanges set to true to check
  148. // there are no changes on the second run.
  149. this.detectChanges(true);
  150. }
  151. }
  152. });
  153. this._onStableSubscription = ngZone.onStable.subscribe({
  154. next: () => {
  155. this._isStable = true;
  156. // Check whether there is a pending whenStable() completer to resolve.
  157. if (this._promise !== null) {
  158. // If so check whether there are no pending macrotasks before resolving.
  159. // Do this check in the next tick so that ngZone gets a chance to update the state of
  160. // pending macrotasks.
  161. scheduleMicroTask(() => {
  162. if (!ngZone.hasPendingMacrotasks) {
  163. if (this._promise !== null) {
  164. this._resolve(true);
  165. this._resolve = null;
  166. this._promise = null;
  167. }
  168. }
  169. });
  170. }
  171. }
  172. });
  173. this._onErrorSubscription =
  174. ngZone.onError.subscribe({ next: (error) => { throw error; } });
  175. });
  176. }
  177. }
  178. _tick(checkNoChanges) {
  179. this.changeDetectorRef.detectChanges();
  180. if (checkNoChanges) {
  181. this.checkNoChanges();
  182. }
  183. }
  184. /**
  185. * Trigger a change detection cycle for the component.
  186. */
  187. detectChanges(checkNoChanges = true) {
  188. if (this.ngZone != null) {
  189. // Run the change detection inside the NgZone so that any async tasks as part of the change
  190. // detection are captured by the zone and can be waited for in isStable.
  191. this.ngZone.run(() => { this._tick(checkNoChanges); });
  192. }
  193. else {
  194. // Running without zone. Just do the change detection.
  195. this._tick(checkNoChanges);
  196. }
  197. }
  198. /**
  199. * Do a change detection run to make sure there were no changes.
  200. */
  201. checkNoChanges() { this.changeDetectorRef.checkNoChanges(); }
  202. /**
  203. * Set whether the fixture should autodetect changes.
  204. *
  205. * Also runs detectChanges once so that any existing change is detected.
  206. */
  207. autoDetectChanges(autoDetect = true) {
  208. if (this.ngZone == null) {
  209. throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set');
  210. }
  211. this._autoDetect = autoDetect;
  212. this.detectChanges();
  213. }
  214. /**
  215. * Return whether the fixture is currently stable or has async tasks that have not been completed
  216. * yet.
  217. */
  218. isStable() { return this._isStable && !this.ngZone.hasPendingMacrotasks; }
  219. /**
  220. * Get a promise that resolves when the fixture is stable.
  221. *
  222. * This can be used to resume testing after events have triggered asynchronous activity or
  223. * asynchronous change detection.
  224. */
  225. whenStable() {
  226. if (this.isStable()) {
  227. return Promise.resolve(false);
  228. }
  229. else if (this._promise !== null) {
  230. return this._promise;
  231. }
  232. else {
  233. this._promise = new Promise(res => { this._resolve = res; });
  234. return this._promise;
  235. }
  236. }
  237. _getRenderer() {
  238. if (this._renderer === undefined) {
  239. this._renderer = this.componentRef.injector.get(RendererFactory2, null);
  240. }
  241. return this._renderer;
  242. }
  243. /**
  244. * Get a promise that resolves when the ui state is stable following animations.
  245. */
  246. whenRenderingDone() {
  247. const renderer = this._getRenderer();
  248. if (renderer && renderer.whenRenderingDone) {
  249. return renderer.whenRenderingDone();
  250. }
  251. return this.whenStable();
  252. }
  253. /**
  254. * Trigger component destruction.
  255. */
  256. destroy() {
  257. if (!this._isDestroyed) {
  258. this.componentRef.destroy();
  259. if (this._onUnstableSubscription != null) {
  260. this._onUnstableSubscription.unsubscribe();
  261. this._onUnstableSubscription = null;
  262. }
  263. if (this._onStableSubscription != null) {
  264. this._onStableSubscription.unsubscribe();
  265. this._onStableSubscription = null;
  266. }
  267. if (this._onMicrotaskEmptySubscription != null) {
  268. this._onMicrotaskEmptySubscription.unsubscribe();
  269. this._onMicrotaskEmptySubscription = null;
  270. }
  271. if (this._onErrorSubscription != null) {
  272. this._onErrorSubscription.unsubscribe();
  273. this._onErrorSubscription = null;
  274. }
  275. this._isDestroyed = true;
  276. }
  277. }
  278. }
  279. function scheduleMicroTask(fn) {
  280. Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
  281. }
  282. /**
  283. * @license
  284. * Copyright Google Inc. All Rights Reserved.
  285. *
  286. * Use of this source code is governed by an MIT-style license that can be
  287. * found in the LICENSE file at https://angular.io/license
  288. */
  289. const FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec'];
  290. const ProxyZoneSpec = Zone['ProxyZoneSpec'];
  291. let _fakeAsyncTestZoneSpec = null;
  292. /**
  293. * Clears out the shared fake async zone for a test.
  294. * To be called in a global `beforeEach`.
  295. *
  296. * @experimental
  297. */
  298. function resetFakeAsyncZone() {
  299. _fakeAsyncTestZoneSpec = null;
  300. ProxyZoneSpec.assertPresent().resetDelegate();
  301. }
  302. let _inFakeAsyncCall = false;
  303. /**
  304. * Wraps a function to be executed in the fakeAsync zone:
  305. * - microtasks are manually executed by calling `flushMicrotasks()`,
  306. * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
  307. *
  308. * If there are any pending timers at the end of the function, an exception will be thrown.
  309. *
  310. * Can be used to wrap inject() calls.
  311. *
  312. * ## Example
  313. *
  314. * {@example core/testing/ts/fake_async.ts region='basic'}
  315. *
  316. * @param fn
  317. * @returns The function wrapped to be executed in the fakeAsync zone
  318. *
  319. * @experimental
  320. */
  321. function fakeAsync(fn) {
  322. // Not using an arrow function to preserve context passed from call site
  323. return function (...args) {
  324. const proxyZoneSpec = ProxyZoneSpec.assertPresent();
  325. if (_inFakeAsyncCall) {
  326. throw new Error('fakeAsync() calls can not be nested');
  327. }
  328. _inFakeAsyncCall = true;
  329. try {
  330. if (!_fakeAsyncTestZoneSpec) {
  331. if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
  332. throw new Error('fakeAsync() calls can not be nested');
  333. }
  334. _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
  335. }
  336. let res;
  337. const lastProxyZoneSpec = proxyZoneSpec.getDelegate();
  338. proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
  339. try {
  340. res = fn.apply(this, args);
  341. flushMicrotasks();
  342. }
  343. finally {
  344. proxyZoneSpec.setDelegate(lastProxyZoneSpec);
  345. }
  346. if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
  347. throw new Error(`${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` +
  348. `periodic timer(s) still in the queue.`);
  349. }
  350. if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
  351. throw new Error(`${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`);
  352. }
  353. return res;
  354. }
  355. finally {
  356. _inFakeAsyncCall = false;
  357. resetFakeAsyncZone();
  358. }
  359. };
  360. }
  361. function _getFakeAsyncZoneSpec() {
  362. if (_fakeAsyncTestZoneSpec == null) {
  363. throw new Error('The code should be running in the fakeAsync zone to call this function');
  364. }
  365. return _fakeAsyncTestZoneSpec;
  366. }
  367. /**
  368. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
  369. *
  370. * The microtasks queue is drained at the very start of this function and after any timer callback
  371. * has been executed.
  372. *
  373. * ## Example
  374. *
  375. * {@example core/testing/ts/fake_async.ts region='basic'}
  376. *
  377. * @experimental
  378. */
  379. function tick(millis = 0) {
  380. _getFakeAsyncZoneSpec().tick(millis);
  381. }
  382. /**
  383. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
  384. * draining the macrotask queue until it is empty. The returned value is the milliseconds
  385. * of time that would have been elapsed.
  386. *
  387. * @param maxTurns
  388. * @returns The simulated time elapsed, in millis.
  389. *
  390. * @experimental
  391. */
  392. function flush(maxTurns) {
  393. return _getFakeAsyncZoneSpec().flush(maxTurns);
  394. }
  395. /**
  396. * Discard all remaining periodic tasks.
  397. *
  398. * @experimental
  399. */
  400. function discardPeriodicTasks() {
  401. const zoneSpec = _getFakeAsyncZoneSpec();
  402. const pendingTimers = zoneSpec.pendingPeriodicTimers;
  403. zoneSpec.pendingPeriodicTimers.length = 0;
  404. }
  405. /**
  406. * Flush any pending microtasks.
  407. *
  408. * @experimental
  409. */
  410. function flushMicrotasks() {
  411. _getFakeAsyncZoneSpec().flushMicrotasks();
  412. }
  413. /**
  414. * @license
  415. * Copyright Google Inc. All Rights Reserved.
  416. *
  417. * Use of this source code is governed by an MIT-style license that can be
  418. * found in the LICENSE file at https://angular.io/license
  419. */
  420. /**
  421. * Injectable completer that allows signaling completion of an asynchronous test. Used internally.
  422. */
  423. class AsyncTestCompleter {
  424. constructor() {
  425. this._promise = new Promise((res, rej) => {
  426. this._resolve = res;
  427. this._reject = rej;
  428. });
  429. }
  430. done(value) { this._resolve(value); }
  431. fail(error, stackTrace) { this._reject(error); }
  432. get promise() { return this._promise; }
  433. }
  434. /**
  435. * @license
  436. * Copyright Google Inc. All Rights Reserved.
  437. *
  438. * Use of this source code is governed by an MIT-style license that can be
  439. * found in the LICENSE file at https://angular.io/license
  440. */
  441. function unimplemented() {
  442. throw Error('unimplemented');
  443. }
  444. /**
  445. * Special interface to the compiler only used by testing
  446. *
  447. * @experimental
  448. */
  449. class TestingCompiler extends Compiler {
  450. get injector() { throw unimplemented(); }
  451. overrideModule(module, overrides) {
  452. throw unimplemented();
  453. }
  454. overrideDirective(directive, overrides) {
  455. throw unimplemented();
  456. }
  457. overrideComponent(component, overrides) {
  458. throw unimplemented();
  459. }
  460. overridePipe(directive, overrides) {
  461. throw unimplemented();
  462. }
  463. /**
  464. * Allows to pass the compile summary from AOT compilation to the JIT compiler,
  465. * so that it can use the code generated by AOT.
  466. */
  467. loadAotSummaries(summaries) { throw unimplemented(); }
  468. /**
  469. * Gets the component factory for the given component.
  470. * This assumes that the component has been compiled before calling this call using
  471. * `compileModuleAndAllComponents*`.
  472. */
  473. getComponentFactory(component) { throw unimplemented(); }
  474. /**
  475. * Returns the component type that is stored in the given error.
  476. * This can be used for errors created by compileModule...
  477. */
  478. getComponentFromError(error) { throw unimplemented(); }
  479. }
  480. TestingCompiler.decorators = [
  481. { type: Injectable },
  482. ];
  483. /** @nocollapse */
  484. TestingCompiler.ctorParameters = () => [];
  485. /**
  486. * A factory for creating a Compiler
  487. *
  488. * @experimental
  489. */
  490. class TestingCompilerFactory {
  491. }
  492. /**
  493. * @license
  494. * Copyright Google Inc. All Rights Reserved.
  495. *
  496. * Use of this source code is governed by an MIT-style license that can be
  497. * found in the LICENSE file at https://angular.io/license
  498. */
  499. const UNDEFINED = new Object();
  500. /**
  501. * An abstract class for inserting the root test component element in a platform independent way.
  502. *
  503. * @experimental
  504. */
  505. class TestComponentRenderer {
  506. insertRootElement(rootElementId) { }
  507. }
  508. let _nextRootElementId = 0;
  509. /**
  510. * @experimental
  511. */
  512. const ComponentFixtureAutoDetect = new InjectionToken('ComponentFixtureAutoDetect');
  513. /**
  514. * @experimental
  515. */
  516. const ComponentFixtureNoNgZone = new InjectionToken('ComponentFixtureNoNgZone');
  517. /**
  518. * @whatItDoes Configures and initializes environment for unit testing and provides methods for
  519. * creating components and services in unit tests.
  520. * @description
  521. *
  522. * TestBed is the primary api for writing unit tests for Angular applications and libraries.
  523. *
  524. * @stable
  525. */
  526. class TestBed {
  527. constructor() {
  528. this._instantiated = false;
  529. this._compiler = null;
  530. this._moduleRef = null;
  531. this._moduleFactory = null;
  532. this._compilerOptions = [];
  533. this._moduleOverrides = [];
  534. this._componentOverrides = [];
  535. this._directiveOverrides = [];
  536. this._pipeOverrides = [];
  537. this._providers = [];
  538. this._declarations = [];
  539. this._imports = [];
  540. this._schemas = [];
  541. this._activeFixtures = [];
  542. this._testEnvAotSummaries = () => [];
  543. this._aotSummaries = [];
  544. this._templateOverrides = [];
  545. this.platform = null;
  546. this.ngModule = null;
  547. }
  548. /**
  549. * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
  550. * angular module. These are common to every test in the suite.
  551. *
  552. * This may only be called once, to set up the common providers for the current test
  553. * suite on the current platform. If you absolutely need to change the providers,
  554. * first use `resetTestEnvironment`.
  555. *
  556. * Test modules and platforms for individual platforms are available from
  557. * '@angular/<platform_name>/testing'.
  558. *
  559. * @experimental
  560. */
  561. static initTestEnvironment(ngModule, platform, aotSummaries) {
  562. const testBed = getTestBed();
  563. testBed.initTestEnvironment(ngModule, platform, aotSummaries);
  564. return testBed;
  565. }
  566. /**
  567. * Reset the providers for the test injector.
  568. *
  569. * @experimental
  570. */
  571. static resetTestEnvironment() { getTestBed().resetTestEnvironment(); }
  572. static resetTestingModule() {
  573. getTestBed().resetTestingModule();
  574. return TestBed;
  575. }
  576. /**
  577. * Allows overriding default compiler providers and settings
  578. * which are defined in test_injector.js
  579. */
  580. static configureCompiler(config) {
  581. getTestBed().configureCompiler(config);
  582. return TestBed;
  583. }
  584. /**
  585. * Allows overriding default providers, directives, pipes, modules of the test injector,
  586. * which are defined in test_injector.js
  587. */
  588. static configureTestingModule(moduleDef) {
  589. getTestBed().configureTestingModule(moduleDef);
  590. return TestBed;
  591. }
  592. /**
  593. * Compile components with a `templateUrl` for the test's NgModule.
  594. * It is necessary to call this function
  595. * as fetching urls is asynchronous.
  596. */
  597. static compileComponents() { return getTestBed().compileComponents(); }
  598. static overrideModule(ngModule, override) {
  599. getTestBed().overrideModule(ngModule, override);
  600. return TestBed;
  601. }
  602. static overrideComponent(component, override) {
  603. getTestBed().overrideComponent(component, override);
  604. return TestBed;
  605. }
  606. static overrideDirective(directive, override) {
  607. getTestBed().overrideDirective(directive, override);
  608. return TestBed;
  609. }
  610. static overridePipe(pipe, override) {
  611. getTestBed().overridePipe(pipe, override);
  612. return TestBed;
  613. }
  614. static overrideTemplate(component, template) {
  615. getTestBed().overrideComponent(component, { set: { template, templateUrl: (null) } });
  616. return TestBed;
  617. }
  618. /**
  619. * Overrides the template of the given component, compiling the template
  620. * in the context of the TestingModule.
  621. *
  622. * Note: This works for JIT and AOTed components as well.
  623. */
  624. static overrideTemplateUsingTestingModule(component, template) {
  625. getTestBed().overrideTemplateUsingTestingModule(component, template);
  626. return TestBed;
  627. }
  628. static overrideProvider(token, provider) {
  629. getTestBed().overrideProvider(token, provider);
  630. return TestBed;
  631. }
  632. static deprecatedOverrideProvider(token, provider) {
  633. getTestBed().deprecatedOverrideProvider(token, provider);
  634. return TestBed;
  635. }
  636. static get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
  637. return getTestBed().get(token, notFoundValue);
  638. }
  639. static createComponent(component) {
  640. return getTestBed().createComponent(component);
  641. }
  642. /**
  643. * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
  644. * angular module. These are common to every test in the suite.
  645. *
  646. * This may only be called once, to set up the common providers for the current test
  647. * suite on the current platform. If you absolutely need to change the providers,
  648. * first use `resetTestEnvironment`.
  649. *
  650. * Test modules and platforms for individual platforms are available from
  651. * '@angular/<platform_name>/testing'.
  652. *
  653. * @experimental
  654. */
  655. initTestEnvironment(ngModule, platform, aotSummaries) {
  656. if (this.platform || this.ngModule) {
  657. throw new Error('Cannot set base providers because it has already been called');
  658. }
  659. this.platform = platform;
  660. this.ngModule = ngModule;
  661. if (aotSummaries) {
  662. this._testEnvAotSummaries = aotSummaries;
  663. }
  664. }
  665. /**
  666. * Reset the providers for the test injector.
  667. *
  668. * @experimental
  669. */
  670. resetTestEnvironment() {
  671. this.resetTestingModule();
  672. this.platform = (null);
  673. this.ngModule = (null);
  674. this._testEnvAotSummaries = () => [];
  675. }
  676. resetTestingModule() {
  677. ɵclearOverrides();
  678. this._aotSummaries = [];
  679. this._templateOverrides = [];
  680. this._compiler = (null);
  681. this._moduleOverrides = [];
  682. this._componentOverrides = [];
  683. this._directiveOverrides = [];
  684. this._pipeOverrides = [];
  685. this._moduleRef = (null);
  686. this._moduleFactory = (null);
  687. this._compilerOptions = [];
  688. this._providers = [];
  689. this._declarations = [];
  690. this._imports = [];
  691. this._schemas = [];
  692. this._instantiated = false;
  693. this._activeFixtures.forEach((fixture) => {
  694. try {
  695. fixture.destroy();
  696. }
  697. catch (e) {
  698. console.error('Error during cleanup of component', {
  699. component: fixture.componentInstance,
  700. stacktrace: e,
  701. });
  702. }
  703. });
  704. this._activeFixtures = [];
  705. }
  706. configureCompiler(config) {
  707. this._assertNotInstantiated('TestBed.configureCompiler', 'configure the compiler');
  708. this._compilerOptions.push(config);
  709. }
  710. configureTestingModule(moduleDef) {
  711. this._assertNotInstantiated('TestBed.configureTestingModule', 'configure the test module');
  712. if (moduleDef.providers) {
  713. this._providers.push(...moduleDef.providers);
  714. }
  715. if (moduleDef.declarations) {
  716. this._declarations.push(...moduleDef.declarations);
  717. }
  718. if (moduleDef.imports) {
  719. this._imports.push(...moduleDef.imports);
  720. }
  721. if (moduleDef.schemas) {
  722. this._schemas.push(...moduleDef.schemas);
  723. }
  724. if (moduleDef.aotSummaries) {
  725. this._aotSummaries.push(moduleDef.aotSummaries);
  726. }
  727. }
  728. compileComponents() {
  729. if (this._moduleFactory || this._instantiated) {
  730. return Promise.resolve(null);
  731. }
  732. const moduleType = this._createCompilerAndModule();
  733. return this._compiler.compileModuleAndAllComponentsAsync(moduleType)
  734. .then((moduleAndComponentFactories) => {
  735. this._moduleFactory = moduleAndComponentFactories.ngModuleFactory;
  736. });
  737. }
  738. _initIfNeeded() {
  739. if (this._instantiated) {
  740. return;
  741. }
  742. if (!this._moduleFactory) {
  743. try {
  744. const moduleType = this._createCompilerAndModule();
  745. this._moduleFactory =
  746. this._compiler.compileModuleAndAllComponentsSync(moduleType).ngModuleFactory;
  747. }
  748. catch (e) {
  749. const errorCompType = this._compiler.getComponentFromError(e);
  750. if (errorCompType) {
  751. throw new Error(`This test module uses the component ${ɵstringify(errorCompType)} which is using a "templateUrl" or "styleUrls", but they were never compiled. ` +
  752. `Please call "TestBed.compileComponents" before your test.`);
  753. }
  754. else {
  755. throw e;
  756. }
  757. }
  758. }
  759. for (const { component, templateOf } of this._templateOverrides) {
  760. const compFactory = this._compiler.getComponentFactory(templateOf);
  761. ɵoverrideComponentView(component, compFactory);
  762. }
  763. const ngZone = new NgZone({ enableLongStackTrace: true });
  764. const providers = [{ provide: NgZone, useValue: ngZone }];
  765. const ngZoneInjector = Injector.create({
  766. providers: providers,
  767. parent: this.platform.injector,
  768. name: this._moduleFactory.moduleType.name
  769. });
  770. this._moduleRef = this._moduleFactory.create(ngZoneInjector);
  771. // ApplicationInitStatus.runInitializers() is marked @internal to core. So casting to any
  772. // before accessing it.
  773. // ApplicationInitStatus.runInitializers() is marked @internal to core. So casting to any
  774. // before accessing it.
  775. this._moduleRef.injector.get(ApplicationInitStatus).runInitializers();
  776. this._instantiated = true;
  777. }
  778. _createCompilerAndModule() {
  779. const providers = this._providers.concat([{ provide: TestBed, useValue: this }]);
  780. const declarations = [...this._declarations, ...this._templateOverrides.map(entry => entry.templateOf)];
  781. const imports = [this.ngModule, this._imports];
  782. const schemas = this._schemas;
  783. class DynamicTestModule {
  784. }
  785. DynamicTestModule.decorators = [
  786. { type: NgModule, args: [{ providers, declarations, imports, schemas },] },
  787. ];
  788. /** @nocollapse */
  789. DynamicTestModule.ctorParameters = () => [];
  790. const compilerFactory = this.platform.injector.get(TestingCompilerFactory);
  791. this._compiler = compilerFactory.createTestingCompiler(this._compilerOptions);
  792. for (const summary of [this._testEnvAotSummaries, ...this._aotSummaries]) {
  793. this._compiler.loadAotSummaries(summary);
  794. }
  795. this._moduleOverrides.forEach((entry) => this._compiler.overrideModule(entry[0], entry[1]));
  796. this._componentOverrides.forEach((entry) => this._compiler.overrideComponent(entry[0], entry[1]));
  797. this._directiveOverrides.forEach((entry) => this._compiler.overrideDirective(entry[0], entry[1]));
  798. this._pipeOverrides.forEach((entry) => this._compiler.overridePipe(entry[0], entry[1]));
  799. return DynamicTestModule;
  800. }
  801. _assertNotInstantiated(methodName, methodDescription) {
  802. if (this._instantiated) {
  803. throw new Error(`Cannot ${methodDescription} when the test module has already been instantiated. ` +
  804. `Make sure you are not using \`inject\` before \`${methodName}\`.`);
  805. }
  806. }
  807. get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
  808. this._initIfNeeded();
  809. if (token === TestBed) {
  810. return this;
  811. }
  812. // Tests can inject things from the ng module and from the compiler,
  813. // but the ng module can't inject things from the compiler and vice versa.
  814. const result = this._moduleRef.injector.get(token, UNDEFINED);
  815. return result === UNDEFINED ? this._compiler.injector.get(token, notFoundValue) : result;
  816. }
  817. execute(tokens, fn, context) {
  818. this._initIfNeeded();
  819. const params = tokens.map(t => this.get(t));
  820. return fn.apply(context, params);
  821. }
  822. overrideModule(ngModule, override) {
  823. this._assertNotInstantiated('overrideModule', 'override module metadata');
  824. this._moduleOverrides.push([ngModule, override]);
  825. }
  826. overrideComponent(component, override) {
  827. this._assertNotInstantiated('overrideComponent', 'override component metadata');
  828. this._componentOverrides.push([component, override]);
  829. }
  830. overrideDirective(directive, override) {
  831. this._assertNotInstantiated('overrideDirective', 'override directive metadata');
  832. this._directiveOverrides.push([directive, override]);
  833. }
  834. overridePipe(pipe, override) {
  835. this._assertNotInstantiated('overridePipe', 'override pipe metadata');
  836. this._pipeOverrides.push([pipe, override]);
  837. }
  838. overrideProvider(token, provider) {
  839. this.overrideProviderImpl(token, provider);
  840. }
  841. deprecatedOverrideProvider(token, provider) {
  842. this.overrideProviderImpl(token, provider, /* deprecated */ /* deprecated */ true);
  843. }
  844. overrideProviderImpl(token, provider, deprecated = false) {
  845. let flags = 0;
  846. let value;
  847. if (provider.useFactory) {
  848. flags |= 1024 /* TypeFactoryProvider */;
  849. value = provider.useFactory;
  850. }
  851. else {
  852. flags |= 256 /* TypeValueProvider */;
  853. value = provider.useValue;
  854. }
  855. const deps = (provider.deps || []).map((dep) => {
  856. let depFlags = 0;
  857. let depToken;
  858. if (Array.isArray(dep)) {
  859. dep.forEach((entry) => {
  860. if (entry instanceof Optional) {
  861. depFlags |= 2 /* Optional */;
  862. }
  863. else if (entry instanceof SkipSelf) {
  864. depFlags |= 1 /* SkipSelf */;
  865. }
  866. else {
  867. depToken = entry;
  868. }
  869. });
  870. }
  871. else {
  872. depToken = dep;
  873. }
  874. return [depFlags, depToken];
  875. });
  876. ɵoverrideProvider({ token, flags, deps, value, deprecatedBehavior: deprecated });
  877. }
  878. overrideTemplateUsingTestingModule(component, template) {
  879. this._assertNotInstantiated('overrideTemplateUsingTestingModule', 'override template');
  880. class OverrideComponent {
  881. }
  882. OverrideComponent.decorators = [
  883. { type: Component, args: [{ selector: 'empty', template },] },
  884. ];
  885. /** @nocollapse */
  886. OverrideComponent.ctorParameters = () => [];
  887. this._templateOverrides.push({ component, templateOf: OverrideComponent });
  888. }
  889. createComponent(component) {
  890. this._initIfNeeded();
  891. const componentFactory = this._compiler.getComponentFactory(component);
  892. if (!componentFactory) {
  893. throw new Error(`Cannot create the component ${ɵstringify(component)} as it was not imported into the testing module!`);
  894. }
  895. const noNgZone = this.get(ComponentFixtureNoNgZone, false);
  896. const autoDetect = this.get(ComponentFixtureAutoDetect, false);
  897. const ngZone = noNgZone ? null : this.get(NgZone, null);
  898. const testComponentRenderer = this.get(TestComponentRenderer);
  899. const rootElId = `root${_nextRootElementId++}`;
  900. testComponentRenderer.insertRootElement(rootElId);
  901. const initComponent = () => {
  902. const componentRef = componentFactory.create(Injector.NULL, [], `#${rootElId}`, this._moduleRef);
  903. return new ComponentFixture(componentRef, ngZone, autoDetect);
  904. };
  905. const fixture = !ngZone ? initComponent() : ngZone.run(initComponent);
  906. this._activeFixtures.push(fixture);
  907. return fixture;
  908. }
  909. }
  910. let _testBed = (null);
  911. /**
  912. * @experimental
  913. */
  914. function getTestBed() {
  915. return _testBed = _testBed || new TestBed();
  916. }
  917. /**
  918. * Allows injecting dependencies in `beforeEach()` and `it()`.
  919. *
  920. * Example:
  921. *
  922. * ```
  923. * beforeEach(inject([Dependency, AClass], (dep, object) => {
  924. * // some code that uses `dep` and `object`
  925. * // ...
  926. * }));
  927. *
  928. * it('...', inject([AClass], (object) => {
  929. * object.doSomething();
  930. * expect(...);
  931. * })
  932. * ```
  933. *
  934. * Notes:
  935. * - inject is currently a function because of some Traceur limitation the syntax should
  936. * eventually
  937. * becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });`
  938. *
  939. * @stable
  940. */
  941. function inject(tokens, fn) {
  942. const testBed = getTestBed();
  943. if (tokens.indexOf(AsyncTestCompleter) >= 0) {
  944. // Not using an arrow function to preserve context passed from call site
  945. return function () {
  946. // Return an async test method that returns a Promise if AsyncTestCompleter is one of
  947. // the injected tokens.
  948. return testBed.compileComponents().then(() => {
  949. const completer = testBed.get(AsyncTestCompleter);
  950. testBed.execute(tokens, fn, this);
  951. return completer.promise;
  952. });
  953. };
  954. }
  955. else {
  956. // Not using an arrow function to preserve context passed from call site
  957. return function () { return testBed.execute(tokens, fn, this); };
  958. }
  959. }
  960. /**
  961. * @experimental
  962. */
  963. class InjectSetupWrapper {
  964. constructor(_moduleDef) {
  965. this._moduleDef = _moduleDef;
  966. }
  967. _addModule() {
  968. const moduleDef = this._moduleDef();
  969. if (moduleDef) {
  970. getTestBed().configureTestingModule(moduleDef);
  971. }
  972. }
  973. inject(tokens, fn) {
  974. const self = this;
  975. // Not using an arrow function to preserve context passed from call site
  976. return function () {
  977. self._addModule();
  978. return inject(tokens, fn).call(this);
  979. };
  980. }
  981. }
  982. function withModule(moduleDef, fn) {
  983. if (fn) {
  984. // Not using an arrow function to preserve context passed from call site
  985. return function () {
  986. const testBed = getTestBed();
  987. if (moduleDef) {
  988. testBed.configureTestingModule(moduleDef);
  989. }
  990. return fn.apply(this);
  991. };
  992. }
  993. return new InjectSetupWrapper(() => moduleDef);
  994. }
  995. /**
  996. * @license
  997. * Copyright Google Inc. All Rights Reserved.
  998. *
  999. * Use of this source code is governed by an MIT-style license that can be
  1000. * found in the LICENSE file at https://angular.io/license
  1001. */
  1002. const _global$1 = (typeof window === 'undefined' ? global : window);
  1003. // Reset the test providers and the fake async zone before each test.
  1004. if (_global$1.beforeEach) {
  1005. _global$1.beforeEach(() => {
  1006. TestBed.resetTestingModule();
  1007. resetFakeAsyncZone();
  1008. });
  1009. }
  1010. // TODO(juliemr): remove this, only used because we need to export something to have compilation
  1011. // work.
  1012. const __core_private_testing_placeholder__ = '';
  1013. /**
  1014. * @license
  1015. * Copyright Google Inc. All Rights Reserved.
  1016. *
  1017. * Use of this source code is governed by an MIT-style license that can be
  1018. * found in the LICENSE file at https://angular.io/license
  1019. */
  1020. /**
  1021. * @license
  1022. * Copyright Google Inc. All Rights Reserved.
  1023. *
  1024. * Use of this source code is governed by an MIT-style license that can be
  1025. * found in the LICENSE file at https://angular.io/license
  1026. */
  1027. /**
  1028. * @license
  1029. * Copyright Google Inc. All Rights Reserved.
  1030. *
  1031. * Use of this source code is governed by an MIT-style license that can be
  1032. * found in the LICENSE file at https://angular.io/license
  1033. */
  1034. // This file only reexports content of the `src` folder. Keep it that way.
  1035. /**
  1036. * Generated bundle index. Do not edit.
  1037. */
  1038. export { async, ComponentFixture, resetFakeAsyncZone, fakeAsync, tick, flush, discardPeriodicTasks, flushMicrotasks, TestComponentRenderer, ComponentFixtureAutoDetect, ComponentFixtureNoNgZone, TestBed, getTestBed, inject, InjectSetupWrapper, withModule, __core_private_testing_placeholder__, TestingCompiler as ɵTestingCompiler, TestingCompilerFactory as ɵTestingCompilerFactory };
  1039. //# sourceMappingURL=testing.js.map