UNPKG

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