UNPKG

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