UNPKG

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