UNPKG

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