UNPKG

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