feat(testing): add implicit test module

Every test now has an implicit module. It can be configured via `configureModule` (from @angular/core/testing)
to add providers, directives, pipes, ...

The compiler now has to be configured separately via `configureCompiler` (from @angular/core/testing)
to add providers or define whether to use jit.

BREAKING CHANGE:
- Application providers can no longer inject compiler internals (i.e. everything
  from `@angular/compiler). Inject `Compiler` instead. This reflects the
  changes to `bootstrap` for module support (3f55aa609f).
- Compiler providers can no longer be added via `addProviders` / `withProviders`.
  Use the new method `configureCompiler` instead.
- Platform directives / pipes need to be provided via
  `configureModule` and can no longer be provided via the
  `PLATFORM_PIPES` / `PLATFORM_DIRECTIVES` tokens.
- `setBaseTestProviders()` was renamed into `initTestEnvironment` and 
  now takes a `PlatformRef` and a factory for a
  `Compiler`.
- E.g. for the browser platform:
  
  BEFORE:
  ```
  import {setBaseTestProviders} from ‘@angular/core/testing’;
  import {TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
      TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS} from ‘@angular/platform-browser-dynamic/testing’;
  
  setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
      TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);   
  ```

  AFTER:
  ```
  import {setBaseTestProviders} from ‘@angular/core/testing’;
  import {browserTestCompiler, browserDynamicTestPlatform,
      BrowserDynamicTestModule} from ‘@angular/platform-browser-dynamic/testing’;
  
  initTestEnvironment(
      browserTestCompiler,
      browserDynamicTestPlatform(),
      BrowserDynamicTestModule);

  ```
- E.g. for the server platform:
  
  BEFORE:
  ```
  import {setBaseTestProviders} from ‘@angular/core/testing’;
  import {TEST_SERVER_PLATFORM_PROVIDERS,
      TEST_SERVER_APPLICATION_PROVIDERS} from ‘@angular/platform-server/testing/server’;
  
  setBaseTestProviders(TEST_SERVER_PLATFORM_PROVIDERS,
      TEST_SERVER_APPLICATION_PROVIDERS);   
  ```

  AFTER:
  ```
  import {setBaseTestProviders} from ‘@angular/core/testing’;
  import {serverTestCompiler, serverTestPlatform,
      ServerTestModule} from ‘@angular/platform-browser-dynamic/testing’;
  
  initTestEnvironment(
      serverTestCompiler,
      serverTestPlatform(),
      ServerTestModule);

  ```

Related to #9726
Closes #9846
This commit is contained in:
Tobias Bosch 2016-07-04 09:37:30 -07:00
parent 37e6da6dfb
commit 8d746e3f67
38 changed files with 1000 additions and 497 deletions

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AppModuleFactory, AppModuleMetadata, Compiler, ComponentFactory, ComponentResolver, Injectable, Provider} from '@angular/core'; import {AppModuleFactory, AppModuleMetadata, Compiler, ComponentFactory, ComponentResolver, ComponentStillLoadingError, Injectable, Injector, OptionalMetadata, Provider, SkipSelfMetadata} from '@angular/core';
import {BaseException} from '../src/facade/exceptions'; import {BaseException} from '../src/facade/exceptions';
import {ConcreteType, IS_DART, Type, isBlank, isString, stringify} from '../src/facade/lang'; import {ConcreteType, IS_DART, Type, isBlank, isString, stringify} from '../src/facade/lang';
@ -43,11 +43,13 @@ export class RuntimeCompiler implements ComponentResolver, Compiler {
private _compiledAppModuleCache = new Map<Type, AppModuleFactory<any>>(); private _compiledAppModuleCache = new Map<Type, AppModuleFactory<any>>();
constructor( constructor(
private _metadataResolver: CompileMetadataResolver, private _injector: Injector, private _metadataResolver: CompileMetadataResolver,
private _templateNormalizer: DirectiveNormalizer, private _templateParser: TemplateParser, private _templateNormalizer: DirectiveNormalizer, private _templateParser: TemplateParser,
private _styleCompiler: StyleCompiler, private _viewCompiler: ViewCompiler, private _styleCompiler: StyleCompiler, private _viewCompiler: ViewCompiler,
private _appModuleCompiler: AppModuleCompiler, private _genConfig: CompilerConfig) {} private _appModuleCompiler: AppModuleCompiler, private _genConfig: CompilerConfig) {}
get injector(): Injector { return this._injector; }
resolveComponent(component: Type|string): Promise<ComponentFactory<any>> { resolveComponent(component: Type|string): Promise<ComponentFactory<any>> {
if (isString(component)) { if (isString(component)) {
return PromiseWrapper.reject( return PromiseWrapper.reject(
@ -76,12 +78,15 @@ export class RuntimeCompiler implements ComponentResolver, Compiler {
let componentCompilePromises: Promise<any>[] = []; let componentCompilePromises: Promise<any>[] = [];
if (!appModuleFactory || !useCache) { if (!appModuleFactory || !useCache) {
var compileModuleMeta = this._metadataResolver.getAppModuleMetadata(moduleType, metadata); var compileModuleMeta = this._metadataResolver.getAppModuleMetadata(moduleType, metadata);
let boundCompiler = new BoundCompiler( let boundCompilerFactory = (parentResolver: ComponentResolver) => new BoundCompiler(
this, compileModuleMeta.directives.map(dir => dir.type.runtime), this, compileModuleMeta.directives.map(dir => dir.type.runtime),
compileModuleMeta.pipes.map((pipe) => pipe.type.runtime)); compileModuleMeta.pipes.map((pipe) => pipe.type.runtime), parentResolver);
// Always provide a bound Compiler / ComponentResolver // Always provide a bound Compiler and ComponentResolver
compileModuleMeta.providers.push(this._metadataResolver.getProviderMetadata( compileModuleMeta.providers.push(
new Provider(Compiler, {useValue: boundCompiler}))); this._metadataResolver.getProviderMetadata(new Provider(Compiler, {
useFactory: boundCompilerFactory,
deps: [[new OptionalMetadata(), new SkipSelfMetadata(), ComponentResolver]]
})));
compileModuleMeta.providers.push(this._metadataResolver.getProviderMetadata( compileModuleMeta.providers.push(this._metadataResolver.getProviderMetadata(
new Provider(ComponentResolver, {useExisting: Compiler}))); new Provider(ComponentResolver, {useExisting: Compiler})));
var compileResult = this._appModuleCompiler.compile(compileModuleMeta); var compileResult = this._appModuleCompiler.compile(compileModuleMeta);
@ -130,8 +135,7 @@ export class RuntimeCompiler implements ComponentResolver, Compiler {
templates.forEach((template) => { templates.forEach((template) => {
if (template.loading) { if (template.loading) {
if (isSync) { if (isSync) {
throw new BaseException( throw new ComponentStillLoadingError(template.compType.runtime);
`Can't compile synchronously as ${template.compType.name} is still being loaded!`);
} else { } else {
loadingPromises.push(template.loading); loadingPromises.push(template.loading);
} }
@ -355,12 +359,19 @@ function assertComponent(meta: CompileDirectiveMetadata) {
*/ */
class BoundCompiler implements Compiler, ComponentResolver { class BoundCompiler implements Compiler, ComponentResolver {
constructor( constructor(
private _delegate: RuntimeCompiler, private _directives: any[], private _pipes: any[]) {} private _delegate: RuntimeCompiler, private _directives: any[], private _pipes: any[],
private _parentComponentResolver: ComponentResolver) {}
get injector(): Injector { return this._delegate.injector; }
resolveComponent(component: Type|string): Promise<ComponentFactory<any>> { resolveComponent(component: Type|string): Promise<ComponentFactory<any>> {
if (isString(component)) { if (isString(component)) {
return PromiseWrapper.reject( if (this._parentComponentResolver) {
new BaseException(`Cannot resolve component using '${component}'.`), null); return this._parentComponentResolver.resolveComponent(component);
} else {
return PromiseWrapper.reject(
new BaseException(`Cannot resolve component using '${component}'.`), null);
}
} }
return this.compileComponentAsync(<ConcreteType<any>>component); return this.compileComponentAsync(<ConcreteType<any>>component);
} }
@ -388,7 +399,12 @@ class BoundCompiler implements Compiler, ComponentResolver {
/** /**
* Clears all caches * Clears all caches
*/ */
clearCache(): void { this._delegate.clearCache(); } clearCache(): void {
this._delegate.clearCache();
if (this._parentComponentResolver) {
this._parentComponentResolver.clearCache();
}
}
/** /**
* Clears the cache for the given component/appModule. * Clears the cache for the given component/appModule.

View File

@ -12,18 +12,19 @@ import {DirectiveNormalizer} from '@angular/compiler/src/directive_normalizer';
import {XHR} from '@angular/compiler/src/xhr'; import {XHR} from '@angular/compiler/src/xhr';
import {MockXHR} from '@angular/compiler/testing/xhr_mock'; import {MockXHR} from '@angular/compiler/testing/xhr_mock';
import {ViewEncapsulation} from '@angular/core/src/metadata/view'; import {ViewEncapsulation} from '@angular/core/src/metadata/view';
import {configureCompiler} from '@angular/core/testing';
import {beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {SpyXHR} from './spies'; import {SpyXHR} from './spies';
import {TEST_PROVIDERS} from './test_bindings'; import {TEST_COMPILER_PROVIDERS} from './test_bindings';
export function main() { export function main() {
describe('DirectiveNormalizer', () => { describe('DirectiveNormalizer', () => {
var dirType: CompileTypeMetadata; var dirType: CompileTypeMetadata;
var dirTypeWithHttpUrl: CompileTypeMetadata; var dirTypeWithHttpUrl: CompileTypeMetadata;
beforeEachProviders(() => TEST_PROVIDERS); beforeEach(() => { configureCompiler({providers: TEST_COMPILER_PROVIDERS}); });
beforeEach(() => { beforeEach(() => {
dirType = new CompileTypeMetadata({moduleUrl: 'package:some/module/a.js', name: 'SomeComp'}); dirType = new CompileTypeMetadata({moduleUrl: 'package:some/module/a.js', name: 'SomeComp'});
@ -179,7 +180,7 @@ export function main() {
describe('normalizeExternalStylesheets', () => { describe('normalizeExternalStylesheets', () => {
beforeEachProviders(() => [{provide: XHR, useClass: SpyXHR}]); beforeEach(() => { configureCompiler({providers: [{provide: XHR, useClass: SpyXHR}]}); });
it('should load an external stylesheet', it('should load an external stylesheet',
inject( inject(

View File

@ -9,17 +9,18 @@
import {CompilerConfig} from '@angular/compiler/src/config'; import {CompilerConfig} from '@angular/compiler/src/config';
import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, Component, Directive, DoCheck, Injectable, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewEncapsulation} from '@angular/core'; import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, Component, Directive, DoCheck, Injectable, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewEncapsulation} from '@angular/core';
import {LIFECYCLE_HOOKS_VALUES} from '@angular/core/src/metadata/lifecycle_hooks'; import {LIFECYCLE_HOOKS_VALUES} from '@angular/core/src/metadata/lifecycle_hooks';
import {configureCompiler} from '@angular/core/testing';
import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {IS_DART, stringify} from '../src/facade/lang'; import {IS_DART, stringify} from '../src/facade/lang';
import {CompileMetadataResolver} from '../src/metadata_resolver'; import {CompileMetadataResolver} from '../src/metadata_resolver';
import {MalformedStylesComponent} from './metadata_resolver_fixture'; import {MalformedStylesComponent} from './metadata_resolver_fixture';
import {TEST_PROVIDERS} from './test_bindings'; import {TEST_COMPILER_PROVIDERS} from './test_bindings';
export function main() { export function main() {
describe('CompileMetadataResolver', () => { describe('CompileMetadataResolver', () => {
beforeEachProviders(() => TEST_PROVIDERS); beforeEach(() => { configureCompiler({providers: TEST_COMPILER_PROVIDERS}); });
describe('getMetadata', () => { describe('getMetadata', () => {
it('should read metadata', it('should read metadata',
@ -110,11 +111,15 @@ export function main() {
})); }));
describe('platform directives', () => { describe('platform directives', () => {
beforeEachProviders(() => [{ beforeEach(() => {
provide: CompilerConfig, configureCompiler({
useValue: new CompilerConfig( providers: [{
{genDebugInfo: true, platformDirectives: [ADirective]}) provide: CompilerConfig,
}]); useValue:
new CompilerConfig({genDebugInfo: true, platformDirectives: [ADirective]})
}]
});
});
it('should include platform directives when available', it('should include platform directives when available',
inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => {

View File

@ -1,7 +1,7 @@
import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal';
import {Injectable, Component, Input, ViewMetadata, Compiler, ComponentFactory, Injector, AppModule, AppModuleMetadata, AppModuleFactory} from '@angular/core'; import {Injectable, Component, Input, ViewMetadata, Compiler, ComponentFactory, Injector, AppModule, AppModuleMetadata, AppModuleFactory} from '@angular/core';
import {ConcreteType, stringify} from '../src/facade/lang'; import {ConcreteType, stringify} from '../src/facade/lang';
import {fakeAsync, tick, TestComponentBuilder, ComponentFixture} from '@angular/core/testing'; import {fakeAsync, tick, TestComponentBuilder, ComponentFixture, configureCompiler} from '@angular/core/testing';
import {XHR, ViewResolver} from '@angular/compiler'; import {XHR, ViewResolver} from '@angular/compiler';
import {MockViewResolver} from '@angular/compiler/testing'; import {MockViewResolver} from '@angular/compiler/testing';
@ -31,7 +31,7 @@ export function main() {
let viewResolver: MockViewResolver; let viewResolver: MockViewResolver;
let injector: Injector; let injector: Injector;
beforeEachProviders(() => [{provide: XHR, useValue: new SpyXHR()}]); beforeEach(() => { configureCompiler({providers: [{provide: XHR, useClass: SpyXHR}]}); });
beforeEach(inject( beforeEach(inject(
[Compiler, TestComponentBuilder, XHR, ViewResolver, Injector], [Compiler, TestComponentBuilder, XHR, ViewResolver, Injector],

View File

@ -14,13 +14,14 @@ import {TEMPLATE_TRANSFORMS, TemplateParser, splitClasses} from '@angular/compil
import {MockSchemaRegistry} from '@angular/compiler/testing'; import {MockSchemaRegistry} from '@angular/compiler/testing';
import {SecurityContext} from '@angular/core'; import {SecurityContext} from '@angular/core';
import {Console} from '@angular/core/src/console'; import {Console} from '@angular/core/src/console';
import {configureCompiler} from '@angular/core/testing';
import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {Identifiers, identifierToken} from '../src/identifiers'; import {Identifiers, identifierToken} from '../src/identifiers';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../src/interpolation_config'; import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../src/interpolation_config';
import {unparse} from './expression_parser/unparser'; import {unparse} from './expression_parser/unparser';
import {TEST_PROVIDERS} from './test_bindings'; import {TEST_COMPILER_PROVIDERS} from './test_bindings';
var someModuleUrl = 'package:someModule'; var someModuleUrl = 'package:someModule';
@ -39,9 +40,9 @@ export function main() {
var console: ArrayConsole; var console: ArrayConsole;
function commonBeforeEach() { function commonBeforeEach() {
beforeEachProviders(() => { beforeEach(() => {
console = new ArrayConsole(); console = new ArrayConsole();
return [{provide: Console, useValue: console}]; configureCompiler({providers: [{provide: Console, useValue: console}]});
}); });
beforeEach(inject([TemplateParser], (parser: TemplateParser) => { beforeEach(inject([TemplateParser], (parser: TemplateParser) => {
var component = CompileDirectiveMetadata.create({ var component = CompileDirectiveMetadata.create({
@ -67,10 +68,14 @@ export function main() {
} }
describe('TemplateParser template transform', () => { describe('TemplateParser template transform', () => {
beforeEachProviders(() => [TEST_PROVIDERS, MOCK_SCHEMA_REGISTRY]); beforeEach(() => { configureCompiler({providers: TEST_COMPILER_PROVIDERS}); });
beforeEachProviders( beforeEach(() => {
() => [{provide: TEMPLATE_TRANSFORMS, useValue: new FooAstTransformer(), multi: true}]); configureCompiler({
providers:
[{provide: TEMPLATE_TRANSFORMS, useValue: new FooAstTransformer(), multi: true}]
});
});
describe('single', () => { describe('single', () => {
commonBeforeEach(); commonBeforeEach();
@ -80,8 +85,12 @@ export function main() {
}); });
describe('multiple', () => { describe('multiple', () => {
beforeEachProviders( beforeEach(() => {
() => [{provide: TEMPLATE_TRANSFORMS, useValue: new BarAstTransformer(), multi: true}]); configureCompiler({
providers:
[{provide: TEMPLATE_TRANSFORMS, useValue: new BarAstTransformer(), multi: true}]
});
});
commonBeforeEach(); commonBeforeEach();
it('should compose transformers', () => { it('should compose transformers', () => {
@ -93,9 +102,14 @@ export function main() {
describe('TemplateParser Security', () => { describe('TemplateParser Security', () => {
// Semi-integration test to make sure TemplateParser properly sets the security context. // Semi-integration test to make sure TemplateParser properly sets the security context.
// Uses the actual DomElementSchemaRegistry. // Uses the actual DomElementSchemaRegistry.
beforeEachProviders( beforeEach(() => {
() => configureCompiler({
[TEST_PROVIDERS, {provide: ElementSchemaRegistry, useClass: DomElementSchemaRegistry}]); providers: [
TEST_COMPILER_PROVIDERS,
{provide: ElementSchemaRegistry, useClass: DomElementSchemaRegistry}
]
});
});
commonBeforeEach(); commonBeforeEach();
@ -125,7 +139,9 @@ export function main() {
}); });
describe('TemplateParser', () => { describe('TemplateParser', () => {
beforeEachProviders(() => [TEST_PROVIDERS, MOCK_SCHEMA_REGISTRY]); beforeEach(() => {
configureCompiler({providers: [TEST_COMPILER_PROVIDERS, MOCK_SCHEMA_REGISTRY]});
});
commonBeforeEach(); commonBeforeEach();

View File

@ -11,7 +11,7 @@ import {createUrlResolverWithoutPackagePrefix} from '@angular/compiler/src/url_r
import {MockSchemaRegistry} from '@angular/compiler/testing'; import {MockSchemaRegistry} from '@angular/compiler/testing';
import {MockXHR} from '@angular/compiler/testing/xhr_mock'; import {MockXHR} from '@angular/compiler/testing/xhr_mock';
export var TEST_PROVIDERS: any[] = [ export var TEST_COMPILER_PROVIDERS: any[] = [
{provide: ElementSchemaRegistry, useValue: new MockSchemaRegistry({}, {})}, {provide: ElementSchemaRegistry, useValue: new MockSchemaRegistry({}, {})},
{provide: XHR, useClass: MockXHR}, {provide: XHR, useClass: MockXHR},
{provide: UrlResolver, useFactory: createUrlResolverWithoutPackagePrefix} {provide: UrlResolver, useFactory: createUrlResolverWithoutPackagePrefix}

View File

@ -6,8 +6,8 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AnimationEntryMetadata, Compiler, ComponentFactory, Injectable, Injector, NgZone, ViewMetadata} from '@angular/core'; import {AnimationEntryMetadata, Compiler, ComponentFactory, Inject, Injectable, Injector, NgZone, ViewMetadata} from '@angular/core';
import {ComponentFixture, ComponentFixtureNoNgZone, TestComponentBuilder} from '@angular/core/testing'; import {ComponentFixture, ComponentFixtureNoNgZone, TestComponentBuilder, TestInjector} from '@angular/core/testing';
import {DirectiveResolver, ViewResolver} from '../index'; import {DirectiveResolver, ViewResolver} from '../index';
import {MapWrapper} from '../src/facade/collection'; import {MapWrapper} from '../src/facade/collection';
@ -54,9 +54,7 @@ export class OverridingTestComponentBuilder extends TestComponentBuilder {
/** @internal */ /** @internal */
_viewOverrides = new Map<Type, ViewMetadata>(); _viewOverrides = new Map<Type, ViewMetadata>();
constructor(@Inject(TestInjector) injector: Injector) { super(injector); }
constructor(injector: Injector) { super(injector); }
/** @internal */ /** @internal */
_clone(): OverridingTestComponentBuilder { _clone(): OverridingTestComponentBuilder {

View File

@ -9,7 +9,7 @@
// Public API for compiler // Public API for compiler
export {AppModuleFactory, AppModuleRef} from './linker/app_module_factory'; export {AppModuleFactory, AppModuleRef} from './linker/app_module_factory';
export {AppModuleFactoryLoader} from './linker/app_module_factory_loader'; export {AppModuleFactoryLoader} from './linker/app_module_factory_loader';
export {Compiler} from './linker/compiler'; export {Compiler, ComponentStillLoadingError} from './linker/compiler';
export {ComponentFactory, ComponentRef} from './linker/component_factory'; export {ComponentFactory, ComponentRef} from './linker/component_factory';
export {ComponentFactoryResolver, NoComponentFactoryError} from './linker/component_factory_resolver'; export {ComponentFactoryResolver, NoComponentFactoryError} from './linker/component_factory_resolver';
export {ComponentResolver} from './linker/component_resolver'; export {ComponentResolver} from './linker/component_resolver';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Injector} from '../di';
import {BaseException} from '../facade/exceptions'; import {BaseException} from '../facade/exceptions';
import {ConcreteType, Type, stringify} from '../facade/lang'; import {ConcreteType, Type, stringify} from '../facade/lang';
import {AppModuleMetadata} from '../metadata/app_module'; import {AppModuleMetadata} from '../metadata/app_module';
@ -14,6 +15,17 @@ import {AppModuleFactory} from './app_module_factory';
import {ComponentFactory} from './component_factory'; import {ComponentFactory} from './component_factory';
/**
* Indicates that a component is still being loaded in a synchronous compile.
*
* @stable
*/
export class ComponentStillLoadingError extends BaseException {
constructor(public compType: Type) {
super(`Can't compile synchronously as ${stringify(compType)} is still being loaded!`);
}
}
/** /**
* Low-level service for running the angular compiler duirng runtime * Low-level service for running the angular compiler duirng runtime
* to create {@link ComponentFactory}s, which * to create {@link ComponentFactory}s, which
@ -25,6 +37,13 @@ import {ComponentFactory} from './component_factory';
* @stable * @stable
*/ */
export class Compiler { export class Compiler {
/**
* Returns the injector with which the compiler has been created.
*/
get injector(): Injector {
throw new BaseException(`Runtime compiler is not loaded. Tried to read the injector.`);
}
/** /**
* Loads the template and styles of a component and returns the associated `ComponentFactory`. * Loads the template and styles of a component and returns the associated `ComponentFactory`.
*/ */
@ -34,7 +53,8 @@ export class Compiler {
} }
/** /**
* Compiles the given component. All templates have to be either inline or compiled via * Compiles the given component. All templates have to be either inline or compiled via
* `compileComponentAsync` before. * `compileComponentAsync` before. Otherwise throws a {@link
* CompileSyncComponentStillLoadingError}.
*/ */
compileComponentSync<T>(component: ConcreteType<T>): ComponentFactory<T> { compileComponentSync<T>(component: ConcreteType<T>): ComponentFactory<T> {
throw new BaseException( throw new BaseException(
@ -43,7 +63,7 @@ export class Compiler {
/** /**
* Compiles the given App Module. All templates of the components listed in `precompile` * Compiles the given App Module. All templates of the components listed in `precompile`
* have to be either inline or compiled before via `compileComponentAsync` / * have to be either inline or compiled before via `compileComponentAsync` /
* `compileAppModuleAsync`. * `compileAppModuleAsync`. Otherwise throws a {@link CompileSyncComponentStillLoadingError}.
*/ */
compileAppModuleSync<T>(moduleType: ConcreteType<T>, metadata: AppModuleMetadata = null): compileAppModuleSync<T>(moduleType: ConcreteType<T>, metadata: AppModuleMetadata = null):
AppModuleFactory<T> { AppModuleFactory<T> {

View File

@ -18,7 +18,7 @@ import {DEFAULT_STATE} from '../../src/animation/animation_constants';
import {AnimationEntryMetadata, animate, group, keyframes, sequence, state, style, transition, trigger} from '../../src/animation/metadata'; import {AnimationEntryMetadata, animate, group, keyframes, sequence, state, style, transition, trigger} from '../../src/animation/metadata';
import {AUTO_STYLE} from '../../src/animation/metadata'; import {AUTO_STYLE} from '../../src/animation/metadata';
import {IS_DART, isArray, isPresent} from '../../src/facade/lang'; import {IS_DART, isArray, isPresent} from '../../src/facade/lang';
import {fakeAsync, flushMicrotasks, tick} from '../../testing'; import {configureCompiler, configureModule, fakeAsync, flushMicrotasks, tick} from '../../testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '../../testing/testing_internal'; import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '../../testing/testing_internal';
export function main() { export function main() {
@ -33,13 +33,10 @@ export function main() {
function declareTests({useJit}: {useJit: boolean}) { function declareTests({useJit}: {useJit: boolean}) {
describe('animation tests', function() { describe('animation tests', function() {
beforeEachProviders( beforeEachProviders(() => {
() => configureCompiler({useJit: useJit});
[{ configureModule({providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}]});
provide: CompilerConfig, });
useValue: new CompilerConfig({genDebugInfo: true, useJit: useJit})
},
{provide: AnimationDriver, useClass: MockAnimationDriver}]);
var makeAnimationCmp = var makeAnimationCmp =
(tcb: TestComponentBuilder, tpl: string, (tcb: TestComponentBuilder, tpl: string,

View File

@ -1,7 +1,7 @@
import {LowerCasePipe, NgIf} from '@angular/common'; import {LowerCasePipe, NgIf} from '@angular/common';
import {CompilerConfig} from '@angular/compiler'; import {CompilerConfig} from '@angular/compiler';
import {AppModule, AppModuleMetadata, Compiler, Component, ComponentFactoryResolver, ComponentRef, ComponentResolver, DebugElement, Host, Inject, Injectable, Injector, OpaqueToken, Optional, Provider, SelfMetadata, SkipSelf, SkipSelfMetadata, forwardRef, getDebugNode, provide} from '@angular/core'; import {AppModule, AppModuleMetadata, Compiler, Component, ComponentFactoryResolver, ComponentRef, ComponentResolver, DebugElement, Host, Inject, Injectable, Injector, OpaqueToken, Optional, Provider, ReflectiveInjector, SelfMetadata, SkipSelf, SkipSelfMetadata, forwardRef, getDebugNode, provide} from '@angular/core';
import {ComponentFixture} from '@angular/core/testing'; import {ComponentFixture, configureCompiler} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {BaseException} from '../../src/facade/exceptions'; import {BaseException} from '../../src/facade/exceptions';
@ -119,16 +119,13 @@ function declareTests({useJit}: {useJit: boolean}) {
var compiler: Compiler; var compiler: Compiler;
var injector: Injector; var injector: Injector;
beforeEach(() => { configureCompiler({useJit: useJit}); });
beforeEach(inject([Compiler, Injector], (_compiler: Compiler, _injector: Injector) => { beforeEach(inject([Compiler, Injector], (_compiler: Compiler, _injector: Injector) => {
compiler = _compiler; compiler = _compiler;
injector = _injector; injector = _injector;
})); }));
beforeEachProviders(() => [{
provide: CompilerConfig,
useValue: new CompilerConfig({genDebugInfo: true, useJit: useJit})
}]);
describe('precompile', function() { describe('precompile', function() {
it('should resolve ComponentFactories', () => { it('should resolve ComponentFactories', () => {
let appModule = compiler.compileAppModuleSync(ModuleWithPrecompile).create(); let appModule = compiler.compileAppModuleSync(ModuleWithPrecompile).create();
@ -206,6 +203,7 @@ function declareTests({useJit}: {useJit: boolean}) {
it('should provide a ComponentResolver instance that uses the directives/pipes of the module', it('should provide a ComponentResolver instance that uses the directives/pipes of the module',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let appModule = compiler.compileAppModuleSync(ModuleWithDirectivesAndPipes).create(); let appModule = compiler.compileAppModuleSync(ModuleWithDirectivesAndPipes).create();
let boundCompiler: ComponentResolver = appModule.injector.get(ComponentResolver); let boundCompiler: ComponentResolver = appModule.injector.get(ComponentResolver);
boundCompiler.resolveComponent(CompUsingModuleDirectiveAndPipe).then((cf) => { boundCompiler.resolveComponent(CompUsingModuleDirectiveAndPipe).then((cf) => {
@ -215,6 +213,22 @@ function declareTests({useJit}: {useJit: boolean}) {
}); });
})); }));
it('should provide a ComponentResolver instance that delegates to the parent ComponentResolver for strings',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let parentResolver: any =
jasmine.createSpyObj('resolver', ['resolveComponent', 'clearCache']);
let appModule = compiler.compileAppModuleSync(ModuleWithDirectivesAndPipes)
.create(ReflectiveInjector.resolveAndCreate(
[{provide: ComponentResolver, useValue: parentResolver}]));
parentResolver.resolveComponent.and.returnValue(
Promise.resolve('someFactoryFromParent'));
let boundCompiler: ComponentResolver = appModule.injector.get(ComponentResolver);
boundCompiler.resolveComponent('someString').then((result) => {
expect(parentResolver.resolveComponent).toHaveBeenCalledWith('someString');
expect(result).toBe('someFactoryFromParent');
async.done();
});
}));
}); });
describe('providers', function() { describe('providers', function() {

View File

@ -7,7 +7,7 @@
*/ */
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {ComponentFixture, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing'; import {ComponentFixture, configureCompiler, configureModule, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {isBlank, NumberWrapper, ConcreteType,} from '../../src/facade/lang'; import {isBlank, NumberWrapper, ConcreteType,} from '../../src/facade/lang';
@ -23,14 +23,14 @@ import {IS_DART, Type} from '../../src/facade/lang';
import {EventEmitter, ObservableWrapper} from '../../src/facade/async'; import {EventEmitter, ObservableWrapper} from '../../src/facade/async';
import {Component, DebugElement, Directive, TemplateRef, ChangeDetectorRef, ViewContainerRef, Input, Output, forwardRef, ViewMetadata, Pipe, RootRenderer, Renderer, RenderComponentType, Injectable, provide, OnInit, DoCheck, OnChanges, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked} from '@angular/core'; import {Component, DebugElement, Directive, TemplateRef, ChangeDetectorRef, ViewContainerRef, Input, Output, forwardRef, ViewMetadata, Pipe, RootRenderer, Renderer, RenderComponentType, Injectable, provide, OnInit, DoCheck, OnChanges, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, Injector} from '@angular/core';
import {NgFor, NgIf} from '@angular/common'; import {NgFor, NgIf} from '@angular/common';
import {By} from '@angular/platform-browser/src/dom/debug/by'; import {By} from '@angular/platform-browser/src/dom/debug/by';
import {AsyncPipe} from '@angular/common'; import {AsyncPipe} from '@angular/common';
import {ElementSchemaRegistry} from '@angular/compiler/src/schema/element_schema_registry'; import {ElementSchemaRegistry} from '@angular/compiler/src/schema/element_schema_registry';
import {MockSchemaRegistry} from '@angular/compiler/testing'; import {MockSchemaRegistry} from '@angular/compiler/testing';
import {TEST_PROVIDERS} from '@angular/compiler/test/test_bindings'; import {TEST_COMPILER_PROVIDERS} from '@angular/compiler/test/test_bindings';
import {DebugDomRenderer} from '@angular/core/src/debug/debug_renderer'; import {DebugDomRenderer} from '@angular/core/src/debug/debug_renderer';
import {DomRootRenderer} from '@angular/platform-browser/src/dom/dom_renderer'; import {DomRootRenderer} from '@angular/platform-browser/src/dom/dom_renderer';
@ -88,11 +88,13 @@ export function main() {
// On CJS fakeAsync is not supported... // On CJS fakeAsync is not supported...
if (!getDOM().supportsDOMEvents()) return; if (!getDOM().supportsDOMEvents()) return;
beforeEachProviders( beforeEach(() => {
() => configureCompiler({providers: TEST_COMPILER_PROVIDERS});
[RenderLog, DirectiveLog, {provide: RootRenderer, useClass: LoggingRootRenderer}, configureModule({
TEST_PROVIDERS, providers:
]); [RenderLog, DirectiveLog, {provide: RootRenderer, useClass: LoggingRootRenderer}]
});
});
beforeEach(inject( beforeEach(inject(
[TestComponentBuilder, ElementSchemaRegistry, RenderLog, DirectiveLog], [TestComponentBuilder, ElementSchemaRegistry, RenderLog, DirectiveLog],

View File

@ -7,7 +7,7 @@
*/ */
import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal';
import {fakeAsync, tick, ComponentFixture} from '@angular/core/testing'; import {fakeAsync, tick, ComponentFixture, configureCompiler, configureModule} from '@angular/core/testing';
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
@ -53,13 +53,10 @@ export function main() {
function declareTests({useJit}: {useJit: boolean}) { function declareTests({useJit}: {useJit: boolean}) {
describe('integration tests', function() { describe('integration tests', function() {
beforeEachProviders( beforeEach(() => {
() => configureCompiler({useJit: useJit});
[{ configureModule({providers: [{provide: ANCHOR_ELEMENT, useValue: el('<div></div>')}]});
provide: CompilerConfig, });
useValue: new CompilerConfig({genDebugInfo: true, useJit: useJit})
},
{provide: ANCHOR_ELEMENT, useValue: el('<div></div>')}]);
describe('react to record changes', function() { describe('react to record changes', function() {
it('should consume text node changes', it('should consume text node changes',
@ -1802,10 +1799,16 @@ function declareTests({useJit}: {useJit: boolean}) {
}); });
describe('logging property updates', () => { describe('logging property updates', () => {
beforeEachProviders(() => [{ beforeEach(() => {
provide: CompilerConfig, configureCompiler({
useValue: new CompilerConfig({genDebugInfo: true, useJit: useJit}) providers: [{
}]); provide: CompilerConfig,
// Note: we are testing the `genDebugInfo` flag here, so we
// need to set it explicitely!
useValue: new CompilerConfig({genDebugInfo: true, useJit: useJit})
}]
});
});
it('should reflect property values as attributes', it('should reflect property values as attributes',
inject( inject(

View File

@ -9,14 +9,13 @@
import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {configureCompiler} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {OpaqueToken, ViewMetadata, Component, Directive, AfterContentInit, AfterViewInit, QueryList, ContentChildren, ViewChildren, Input} from '@angular/core'; import {OpaqueToken, ViewMetadata, Component, Directive, AfterContentInit, AfterViewInit, QueryList, ContentChildren, ViewChildren, Input} from '@angular/core';
import {NgIf} from '@angular/common'; import {NgIf} from '@angular/common';
import {CompilerConfig} from '@angular/compiler'; import {CompilerConfig} from '@angular/compiler';
import {el} from '@angular/platform-browser/testing/browser_util'; import {el} from '@angular/platform-browser/testing/browser_util';
const ANCHOR_ELEMENT = new OpaqueToken('AnchorElement');
export function main() { export function main() {
describe('jit', () => { declareTests({useJit: true}); }); describe('jit', () => { declareTests({useJit: true}); });
describe('no jit', () => { declareTests({useJit: false}); }); describe('no jit', () => { declareTests({useJit: false}); });
@ -25,14 +24,7 @@ export function main() {
function declareTests({useJit}: {useJit: boolean}) { function declareTests({useJit}: {useJit: boolean}) {
describe('<ng-container>', function() { describe('<ng-container>', function() {
beforeEachProviders( beforeEach(() => { configureCompiler({useJit: useJit}); });
() =>
[{
provide: CompilerConfig,
useValue: new CompilerConfig({genDebugInfo: true, useJit: useJit})
},
{provide: ANCHOR_ELEMENT, useValue: el('<div></div>')},
]);
it('should be rendered as comment with children as siblings', it('should be rendered as comment with children as siblings',
inject( inject(

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {provide} from '@angular/core'; import {Component, provide} from '@angular/core';
import {ComponentFactory} from '@angular/core/src/linker/component_factory'; import {ComponentFactory} from '@angular/core/src/linker/component_factory';
import {ComponentResolver, ReflectorComponentResolver} from '@angular/core/src/linker/component_resolver'; import {ComponentResolver, ReflectorComponentResolver} from '@angular/core/src/linker/component_resolver';
import {ReflectionInfo, reflector} from '@angular/core/src/reflection/reflection'; import {ReflectionInfo, reflector} from '@angular/core/src/reflection/reflection';
@ -16,34 +16,30 @@ import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('Compiler', () => { describe('Compiler', () => {
var someCompFactory: any /** TODO #9100 */; var someCompFactory: any /** TODO #9100 */;
var compiler: ComponentResolver;
beforeEachProviders(() => [{provide: ComponentResolver, useClass: ReflectorComponentResolver}]); beforeEach(() => {
beforeEach(inject([ComponentResolver], (_compiler: ComponentResolver) => {
someCompFactory = new ComponentFactory(null, null, null); someCompFactory = new ComponentFactory(null, null, null);
reflector.registerType(SomeComponent, new ReflectionInfo([someCompFactory])); reflector.registerType(SomeComponent, new ReflectionInfo([someCompFactory]));
})); compiler = new ReflectorComponentResolver();
});
it('should read the template from an annotation', it('should read the template from an annotation',
inject( inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
[AsyncTestCompleter, ComponentResolver], compiler.resolveComponent(SomeComponent).then((compFactory: ComponentFactory<any>) => {
(async: AsyncTestCompleter, compiler: ComponentResolver) => { expect(compFactory).toBe(someCompFactory);
compiler.resolveComponent(SomeComponent).then((compFactory: ComponentFactory<any>) => { async.done();
expect(compFactory).toBe(someCompFactory); return null;
async.done(); });
return null; }));
});
}));
it('should throw when given a string', it('should throw when given a string',
inject( inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
[AsyncTestCompleter, ComponentResolver], compiler.resolveComponent('someString').catch((e) => {
(async: AsyncTestCompleter, compiler: ComponentResolver) => { expect(e.message).toContain('Cannot resolve component using \'someString\'.')
compiler.resolveComponent('someString').catch((e) => { async.done();
expect(e.message).toContain('Cannot resolve component using \'someString\'.') });
async.done(); }));
});
}));
}); });
} }

View File

@ -7,6 +7,7 @@
*/ */
import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal';
import {configureCompiler, configureModule} from '@angular/core/testing';
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
@ -31,12 +32,10 @@ function declareTests({useJit}: {useJit: boolean}) {
describe('regressions', () => { describe('regressions', () => {
describe('platform pipes', () => { describe('platform pipes', () => {
beforeEachProviders( beforeEach(() => {
() => [{ configureCompiler({useJit: useJit});
provide: CompilerConfig, configureModule({pipes: [PlatformPipe]});
useValue: new CompilerConfig( });
{genDebugInfo: true, useJit: useJit, platformPipes: [PlatformPipe]})
}]);
it('should overwrite them by custom pipes', it('should overwrite them by custom pipes',
inject( inject(

View File

@ -9,6 +9,7 @@
import {ddescribe, describe, expect, inject, beforeEachProviders, beforeEach, afterEach, it,} from '@angular/core/testing/testing_internal'; import {ddescribe, describe, expect, inject, beforeEachProviders, beforeEach, afterEach, it,} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {configureCompiler} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {provide, Injectable, OpaqueToken} from '@angular/core'; import {provide, Injectable, OpaqueToken} from '@angular/core';
import {CompilerConfig} from '@angular/compiler'; import {CompilerConfig} from '@angular/compiler';
@ -18,8 +19,6 @@ import {el} from '@angular/platform-browser/testing/browser_util';
import {DomSanitizationService} from '@angular/platform-browser/src/security/dom_sanitization_service'; import {DomSanitizationService} from '@angular/platform-browser/src/security/dom_sanitization_service';
const ANCHOR_ELEMENT = /*@ts2dart_const*/ new OpaqueToken('AnchorElement');
export function main() { export function main() {
if (IS_DART) { if (IS_DART) {
declareTests({useJit: false}); declareTests({useJit: false});
@ -53,13 +52,7 @@ function itAsync(
function declareTests({useJit}: {useJit: boolean}) { function declareTests({useJit}: {useJit: boolean}) {
describe('security integration tests', function() { describe('security integration tests', function() {
beforeEachProviders( beforeEach(() => { configureCompiler({useJit: useJit}); });
() =>
[{
provide: CompilerConfig,
useValue: new CompilerConfig({genDebugInfo: true, useJit: useJit})
},
{provide: ANCHOR_ELEMENT, useValue: el('<div></div>')}]);
let originalLog: (msg: any) => any; let originalLog: (msg: any) => any;
beforeEach(() => { beforeEach(() => {

View File

@ -6,61 +6,157 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {PLATFORM_INITIALIZER, Provider, ReflectiveInjector, Type} from '../index'; import {AppModule, AppModuleFactory, AppModuleMetadata, AppModuleRef, Compiler, ComponentStillLoadingError, Injector, PlatformRef, Provider, Type} from '../index';
import {lockRunMode} from '../src/application_ref';
import {ListWrapper} from '../src/facade/collection'; import {ListWrapper} from '../src/facade/collection';
import {BaseException} from '../src/facade/exceptions'; import {BaseException} from '../src/facade/exceptions';
import {FunctionWrapper, isPresent} from '../src/facade/lang'; import {FunctionWrapper, isPresent, stringify} from '../src/facade/lang';
import {AsyncTestCompleter} from './async_test_completer'; import {AsyncTestCompleter} from './async_test_completer';
const UNDEFINED = new Object();
/**
* Signature of the compiler factory passed to `initTestEnvironment`.
*
* @experimental
*/
export type TestCompilerFactory =
(config: {providers?: Array<Type|Provider|any[]>, useJit?: boolean}) => Compiler;
/** /**
* @experimental * @experimental
*/ */
export class TestInjector { export class TestInjector implements Injector {
private _instantiated: boolean = false; private _instantiated: boolean = false;
private _injector: ReflectiveInjector = null; private _compiler: Compiler = null;
private _moduleRef: AppModuleRef<any> = null;
private _compilerProviders: Array<Type|Provider|any[]|any> = [];
private _compilerUseJit: boolean = true;
private _providers: Array<Type|Provider|any[]|any> = []; private _providers: Array<Type|Provider|any[]|any> = [];
private _directives: Array<Type|any[]|any> = [];
private _pipes: Array<Type|any[]|any> = [];
private _modules: Array<Type|any[]|any> = [];
private _precompile: Array<Type|any[]|any> = [];
reset() { reset() {
this._injector = null; this._compiler = null;
this._moduleRef = null;
this._compilerProviders = [];
this._compilerUseJit = true;
this._providers = []; this._providers = [];
this._directives = [];
this._pipes = [];
this._modules = [];
this._precompile = [];
this._instantiated = false; this._instantiated = false;
} }
platformProviders: Array<Type|Provider|any[]|any> = []; compilerFactory: TestCompilerFactory = null;
applicationProviders: Array<Type|Provider|any[]|any> = []; platform: PlatformRef = null;
addProviders(providers: Array<Type|Provider|any[]|any>) { appModule: Type = null;
configureCompiler(config: {providers?: any[], useJit?: boolean}) {
if (this._instantiated) { if (this._instantiated) {
throw new BaseException('Cannot add providers after test injector is instantiated'); throw new BaseException('Cannot add configuration after test injector is instantiated');
}
if (config.providers) {
this._compilerProviders = ListWrapper.concat(this._compilerProviders, config.providers);
}
if (config.useJit !== undefined) {
this._compilerUseJit = config.useJit;
} }
this._providers = ListWrapper.concat(this._providers, providers);
} }
createInjector() { configureModule(moduleDef: {
lockRunMode(); providers?: any[],
var rootInjector = ReflectiveInjector.resolveAndCreate(this.platformProviders); directives?: any[],
this._injector = rootInjector.resolveAndCreateChild( pipes?: any[],
ListWrapper.concat(this.applicationProviders, this._providers)); precompile?: any[],
modules?: any[]
}) {
if (this._instantiated) {
throw new BaseException('Cannot add configuration after test injector is instantiated');
}
if (moduleDef.providers) {
this._providers = ListWrapper.concat(this._providers, moduleDef.providers);
}
if (moduleDef.directives) {
this._directives = ListWrapper.concat(this._directives, moduleDef.directives);
}
if (moduleDef.pipes) {
this._pipes = ListWrapper.concat(this._pipes, moduleDef.pipes);
}
if (moduleDef.precompile) {
this._precompile = ListWrapper.concat(this._precompile, moduleDef.precompile);
}
if (moduleDef.modules) {
this._modules = ListWrapper.concat(this._modules, moduleDef.modules);
}
}
createInjectorSync(): Injector {
if (this._instantiated) {
return this;
}
let moduleMeta = this._createCompilerAndModuleMeta();
return this._createFromModuleFactory(
this._compiler.compileAppModuleSync(_NoopModule, moduleMeta));
}
createInjectorAsync(): Promise<Injector> {
if (this._instantiated) {
return Promise.resolve(this);
}
let moduleMeta = this._createCompilerAndModuleMeta();
return this._compiler.compileAppModuleAsync(_NoopModule, moduleMeta)
.then((appModuleFactory) => this._createFromModuleFactory(appModuleFactory));
}
private _createCompilerAndModuleMeta(): AppModuleMetadata {
this._compiler =
this.compilerFactory({providers: this._compilerProviders, useJit: this._compilerUseJit});
const moduleMeta = new AppModuleMetadata({
providers: this._providers.concat([{provide: TestInjector, useValue: this}]),
modules: this._modules.concat([this.appModule]),
directives: this._directives,
pipes: this._pipes,
precompile: this._precompile
});
return moduleMeta;
}
private _createFromModuleFactory(appModuleFactory: AppModuleFactory<any>): Injector {
this._moduleRef = appModuleFactory.create(this.platform.injector);
this._instantiated = true; this._instantiated = true;
return this._injector; return this;
} }
get(token: any) { get(token: any, notFoundValue: any = Injector.THROW_IF_NOT_FOUND) {
if (!this._instantiated) { if (!this._instantiated) {
this.createInjector(); throw new BaseException(
'Illegal state: The TestInjector has not yet been created. Call createInjectorSync/Async first!');
} }
return this._injector.get(token); if (token === TestInjector) {
return this;
}
// Tests can inject things from the app module and from the compiler,
// but the app module can't inject things from the compiler and vice versa.
let result = this._moduleRef.injector.get(token, UNDEFINED);
return result === UNDEFINED ? this._compiler.injector.get(token, notFoundValue) : result;
} }
execute(tokens: any[], fn: Function): any { execute(tokens: any[], fn: Function): any {
if (!this._instantiated) { if (!this._instantiated) {
this.createInjector(); throw new BaseException(
'Illegal state: The TestInjector has not yet been created. Call createInjectorSync/Async first!');
} }
var params = tokens.map(t => this._injector.get(t)); var params = tokens.map(t => this.get(t));
return FunctionWrapper.apply(fn, params); return FunctionWrapper.apply(fn, params);
} }
} }
@ -83,28 +179,22 @@ export function getTestInjector() {
* *
* This may only be called once, to set up the common providers for the current test * This may only be called once, to set up the common providers for the current test
* suite on the current platform. If you absolutely need to change the providers, * suite on the current platform. If you absolutely need to change the providers,
* first use `resetBaseTestProviders`. * first use `resetTestEnvironment`.
* *
* Test Providers for individual platforms are available from * Test Providers for individual platforms are available from
* 'angular2/platform/testing/<platform_name>'. * 'angular2/platform/testing/<platform_name>'.
* *
* @experimental * @experimental
*/ */
export function setBaseTestProviders( export function initTestEnvironment(
platformProviders: Array<Type|Provider|any[]>, compilerFactory: TestCompilerFactory, platform: PlatformRef, appModule: Type) {
applicationProviders: Array<Type|Provider|any[]>) {
var testInjector = getTestInjector(); var testInjector = getTestInjector();
if (testInjector.platformProviders.length > 0 || testInjector.applicationProviders.length > 0) { if (testInjector.compilerFactory || testInjector.platform || testInjector.appModule) {
throw new BaseException('Cannot set base providers because it has already been called'); throw new BaseException('Cannot set base providers because it has already been called');
} }
testInjector.platformProviders = platformProviders; testInjector.compilerFactory = compilerFactory;
testInjector.applicationProviders = applicationProviders; testInjector.platform = platform;
var injector = testInjector.createInjector(); testInjector.appModule = appModule;
let inits: Function[] = injector.get(PLATFORM_INITIALIZER, null);
if (isPresent(inits)) {
inits.forEach(init => init());
}
testInjector.reset();
} }
/** /**
@ -112,10 +202,11 @@ export function setBaseTestProviders(
* *
* @experimental * @experimental
*/ */
export function resetBaseTestProviders() { export function resetTestEnvironment() {
var testInjector = getTestInjector(); var testInjector = getTestInjector();
testInjector.platformProviders = []; testInjector.compilerFactory = null;
testInjector.applicationProviders = []; testInjector.platform = null;
testInjector.appModule = null;
testInjector.reset(); testInjector.reset();
} }
@ -146,16 +237,38 @@ export function resetBaseTestProviders() {
export function inject(tokens: any[], fn: Function): () => any { export function inject(tokens: any[], fn: Function): () => any {
let testInjector = getTestInjector(); let testInjector = getTestInjector();
if (tokens.indexOf(AsyncTestCompleter) >= 0) { if (tokens.indexOf(AsyncTestCompleter) >= 0) {
// Return an async test method that returns a Promise if AsyncTestCompleter is one of the
// injected tokens.
return () => { return () => {
let completer: AsyncTestCompleter = testInjector.get(AsyncTestCompleter); // Return an async test method that returns a Promise if AsyncTestCompleter is one of the
testInjector.execute(tokens, fn); // injected tokens.
return completer.promise; return testInjector.createInjectorAsync().then(() => {
let completer: AsyncTestCompleter = testInjector.get(AsyncTestCompleter);
testInjector.execute(tokens, fn);
return completer.promise;
});
}; };
} else { } else {
// Return a synchronous test method with the injected tokens. return () => {
return () => { return getTestInjector().execute(tokens, fn); }; // Return a asynchronous test method with the injected tokens.
// TODO(tbosch): Right now, we can only detect the AsyncTestZoneSpec via its name.
// (see https://github.com/angular/zone.js/issues/370)
if (Zone.current.name.toLowerCase().indexOf('asynctestzone') >= 0) {
return testInjector.createInjectorAsync().then(() => testInjector.execute(tokens, fn));
} else {
// Return a synchronous test method with the injected tokens.
try {
testInjector.createInjectorSync();
} catch (e) {
if (e instanceof ComponentStillLoadingError) {
throw new Error(
`This test module precompiles the component ${stringify(e.compType)} which is using a "templateUrl", but the test is synchronous. ` +
`Please use the "async(...)" or "fakeAsync(...)" helper functions to make the test asynchronous.`);
} else {
throw e;
}
}
return testInjector.execute(tokens, fn);
}
};
} }
} }
@ -163,18 +276,24 @@ export function inject(tokens: any[], fn: Function): () => any {
* @experimental * @experimental
*/ */
export class InjectSetupWrapper { export class InjectSetupWrapper {
constructor(private _providers: () => any) {} constructor(private _moduleDef: () => {
providers?: any[],
directives?: any[],
pipes?: any[],
precompile?: any[],
modules?: any[]
}) {}
private _addProviders() { private _addModule() {
var additionalProviders = this._providers(); var moduleDef = this._moduleDef();
if (additionalProviders.length > 0) { if (moduleDef) {
getTestInjector().addProviders(additionalProviders); getTestInjector().configureModule(moduleDef);
} }
} }
inject(tokens: any[], fn: Function): () => any { inject(tokens: any[], fn: Function): () => any {
return () => { return () => {
this._addProviders(); this._addModule();
return inject_impl(tokens, fn)(); return inject_impl(tokens, fn)();
}; };
} }
@ -184,9 +303,25 @@ export class InjectSetupWrapper {
* @experimental * @experimental
*/ */
export function withProviders(providers: () => any) { export function withProviders(providers: () => any) {
return new InjectSetupWrapper(providers); return new InjectSetupWrapper(() => {{return {providers: providers()};}});
} }
/**
* @experimental
*/
export function withModule(moduleDef: () => {
providers?: any[],
directives?: any[],
pipes?: any[],
precompile?: any[],
modules?: any[]
}) {
return new InjectSetupWrapper(moduleDef);
}
// This is to ensure inject(Async) within InjectSetupWrapper doesn't call itself // This is to ensure inject(Async) within InjectSetupWrapper doesn't call itself
// when transpiled to Dart. // when transpiled to Dart.
var inject_impl = inject; var inject_impl = inject;
class _NoopModule {}

View File

@ -123,7 +123,7 @@ if (_global.beforeEach) {
export function addProviders(providers: Array<any>): void { export function addProviders(providers: Array<any>): void {
if (!providers) return; if (!providers) return;
try { try {
testInjector.addProviders(providers); testInjector.configureModule({providers: providers});
} catch (e) { } catch (e) {
throw new Error( throw new Error(
'addProviders can\'t be called after the injector has been already created for this test. ' + 'addProviders can\'t be called after the injector has been already created for this test. ' +
@ -132,6 +132,48 @@ export function addProviders(providers: Array<any>): void {
} }
} }
/**
* Allows overriding default providers, directives, pipes, modules of the test injector,
* which are defined in test_injector.js
*
* @stable
*/
export function configureModule(moduleDef: {
providers?: any[],
directives?: any[],
pipes?: any[],
precompile?: any[],
modules?: any[]
}): void {
if (!moduleDef) return;
try {
testInjector.configureModule(moduleDef);
} catch (e) {
throw new Error(
'configureModule can\'t be called after the injector has been already created for this test. ' +
'This is most likely because you\'ve already used the injector to inject a beforeEach or the ' +
'current `it` function.');
}
}
/**
* Allows overriding default compiler providers and settings
* which are defined in test_injector.js
*
* @stable
*/
export function configureCompiler(config: {providers?: any[], useJit?: boolean}): void {
if (!config) return;
try {
testInjector.configureCompiler(config);
} catch (e) {
throw new Error(
'configureCompiler can\'t be called after the injector has been already created for this test. ' +
'This is most likely because you\'ve already used the injector to inject a beforeEach or the ' +
'current `it` function.');
}
}
/** /**
* @deprecated Use beforeEach(() => addProviders()) * @deprecated Use beforeEach(() => addProviders())
*/ */

View File

@ -110,7 +110,7 @@ export function beforeEachProviders(fn: any /** TODO #9100 */): void {
jsmBeforeEach(() => { jsmBeforeEach(() => {
var providers = fn(); var providers = fn();
if (!providers) return; if (!providers) return;
testInjector.addProviders(providers); testInjector.configureModule({providers: providers});
}); });
} }
@ -135,11 +135,10 @@ function _it(jsmFn: Function, name: string, testFn: Function, testTimeOut: numbe
provide: AsyncTestCompleter, provide: AsyncTestCompleter,
useFactory: () => { useFactory: () => {
// Mark the test as async when an AsyncTestCompleter is injected in an it() // Mark the test as async when an AsyncTestCompleter is injected in an it()
if (!inIt) throw new Error('AsyncTestCompleter can only be injected in an "it()"');
return new AsyncTestCompleter(); return new AsyncTestCompleter();
} }
}; };
testInjector.addProviders([completerProvider]); testInjector.configureModule({providers: [completerProvider]});
runner.run(); runner.run();
inIt = true; inIt = true;

View File

@ -7,15 +7,16 @@
*/ */
import {UrlResolver, XHR} from '@angular/compiler'; import {UrlResolver, XHR} from '@angular/compiler';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {Component, provide} from '@angular/core'; import {Component, provide} from '@angular/core';
import {configureCompiler, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {fakeAsync, flushMicrotasks, tick,} from '@angular/core/testing';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {BaseException} from '../../src/facade/exceptions'; import {BaseException} from '../../src/facade/exceptions';
import {CachedXHR} from '../../src/xhr/xhr_cache'; import {CachedXHR} from '../../src/xhr/xhr_cache';
import {setTemplateCache} from './xhr_cache_setter'; import {setTemplateCache} from './xhr_cache_setter';
export function main() { export function main() {
@ -26,10 +27,14 @@ export function main() {
setTemplateCache({'test.html': '<div>Hello</div>'}); setTemplateCache({'test.html': '<div>Hello</div>'});
return new CachedXHR(); return new CachedXHR();
} }
beforeEachProviders(() => [{provide: UrlResolver, useClass: TestUrlResolver}, { beforeEach(() => {
provide: XHR, configureCompiler({
useFactory: createCachedXHR providers: [
}]); {provide: UrlResolver, useClass: TestUrlResolver},
{provide: XHR, useFactory: createCachedXHR}
]
});
});
it('should throw exception if $templateCache is not found', () => { it('should throw exception if $templateCache is not found', () => {
setTemplateCache(null); setTemplateCache(null);

View File

@ -6,35 +6,61 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {DirectiveResolver, ViewResolver} from '@angular/compiler'; import {CompilerConfig, DirectiveResolver, ViewResolver} from '@angular/compiler';
import {MockDirectiveResolver, MockViewResolver, OverridingTestComponentBuilder} from '@angular/compiler/testing'; import {MockDirectiveResolver, MockViewResolver, OverridingTestComponentBuilder} from '@angular/compiler/testing';
import {AppModule, Compiler, Provider, ReflectiveInjector, Type} from '@angular/core';
import {TestComponentBuilder, TestComponentRenderer} from '@angular/core/testing'; import {TestComponentBuilder, TestComponentRenderer} from '@angular/core/testing';
import {TEST_BROWSER_APPLICATION_PROVIDERS, TEST_BROWSER_PLATFORM_PROVIDERS} from '@angular/platform-browser/testing'; import {BrowserTestModule, browserTestPlatform} from '@angular/platform-browser/testing';
import {BROWSER_APP_COMPILER_PROVIDERS} from './index'; import {BROWSER_APP_COMPILER_PROVIDERS} from './index';
import {DOMTestComponentRenderer} from './testing/dom_test_component_renderer'; import {DOMTestComponentRenderer} from './testing/dom_test_component_renderer';
export * from './private_export_testing' export * from './private_export_testing'
/** const TEST_BROWSER_DYNAMIC_COMPILER_PROVIDERS: Array<any /*Type | Provider | any[]*/> = [
* Default platform providers for testing. BROWSER_APP_COMPILER_PROVIDERS,
*
* @stable
*/
export const TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> =
[TEST_BROWSER_PLATFORM_PROVIDERS];
/**
* Default application providers for testing.
*
* @stable
*/
export const TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS: Array<any /*Type | Provider | any[]*/> = [
TEST_BROWSER_APPLICATION_PROVIDERS, BROWSER_APP_COMPILER_PROVIDERS,
[ [
{provide: TestComponentBuilder, useClass: OverridingTestComponentBuilder}, { provide: DirectiveResolver,
{provide: DirectiveResolver, useClass: MockDirectiveResolver}, useClass: MockDirectiveResolver },
{provide: ViewResolver, useClass: MockViewResolver}, { provide: ViewResolver,
{provide: TestComponentRenderer, useClass: DOMTestComponentRenderer}, useClass: MockViewResolver }
] ]
]; ];
/**
* Creates a compiler for testing
*
* @stable
*/
export function browserTestCompiler(
{providers = [], useJit = true}: {providers?: Array<Type|Provider|any[]>,
useJit?: boolean} = {}): Compiler {
const injector = ReflectiveInjector.resolveAndCreate([
TEST_BROWSER_DYNAMIC_COMPILER_PROVIDERS,
{provide: CompilerConfig, useValue: new CompilerConfig({genDebugInfo: true, useJit: useJit})},
providers ? providers : []
]);
return injector.get(Compiler);
}
/**
* Platform for testing.
*
* @experimental API related to bootstrapping are still under review.
*/
export const browserDynamicTestPlatform = browserTestPlatform;
/**
* AppModule for testing.
*
* @stable
*/
@AppModule({
modules: [BrowserTestModule],
providers: [
{provide: TestComponentBuilder, useClass: OverridingTestComponentBuilder},
{provide: TestComponentRenderer, useClass: DOMTestComponentRenderer},
]
})
export class BrowserDynamicTestModule {
}

View File

@ -6,11 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {addProviders, inject, fakeAsync, async, withProviders, tick,} from '@angular/core/testing';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
import {Injectable, provide, Component, ViewMetadata} from '@angular/core';
import {NgIf} from '@angular/common'; import {NgIf} from '@angular/common';
import {CompilerConfig, XHR} from '@angular/compiler';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {AppModule, Component, ComponentFactoryResolver, Directive, Injectable, Input, Pipe, ViewMetadata, provide} from '@angular/core';
import {addProviders, async, configureCompiler, configureModule, fakeAsync, inject, tick, withModule, withProviders} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
import {stringify} from '../../http/src/facade/lang';
import {PromiseWrapper} from '../../http/src/facade/promise'; import {PromiseWrapper} from '../../http/src/facade/promise';
// Services, and components for the tests. // Services, and components for the tests.
@ -98,6 +101,29 @@ class TestViewProvidersComp {
constructor(private fancyService: FancyService) {} constructor(private fancyService: FancyService) {}
} }
@Directive({selector: '[someDir]', host: {'[title]': 'someDir'}})
class SomeDirective {
@Input()
someDir: string;
}
@Pipe({name: 'somePipe'})
class SomePipe {
transform(value: string): any { return `transformed ${value}`; }
}
@Component({selector: 'comp', template: `<div [someDir]="'someValue' | somePipe"></div>`})
class CompUsingModuleDirectiveAndPipe {
}
@AppModule({})
class SomeNestedModule {
}
@Component({selector: 'comp', templateUrl: 'someTemplate.html'})
class CompWithUrlTemplate {
}
export function main() { export function main() {
describe('using the async helper', () => { describe('using the async helper', () => {
var actuallyDone: boolean; var actuallyDone: boolean;
@ -203,6 +229,133 @@ export function main() {
}); });
}); });
describe('using the test injector with modules', () => {
let moduleConfig: any;
beforeEach(() => {
moduleConfig = {
providers: [FancyService],
directives: [SomeDirective],
pipes: [SomePipe],
precompile: [CompUsingModuleDirectiveAndPipe],
modules: [SomeNestedModule]
};
});
describe('setting up a module', () => {
beforeEach(() => configureModule(moduleConfig));
it('should use set up providers', inject([FancyService], (service: FancyService) => {
expect(service.value).toEqual('real value');
}));
it('should use set up directives and pipes',
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
let compFixture = tcb.createSync(CompUsingModuleDirectiveAndPipe);
let el = compFixture.debugElement;
compFixture.detectChanges();
expect(el.children[0].properties['title']).toBe('transformed someValue');
}));
it('should use set up nested modules',
inject([SomeNestedModule], (nestedModule: SomeNestedModule) => {
expect(nestedModule).toBeAnInstanceOf(SomeNestedModule);
}));
it('should use set up precompile components',
inject([ComponentFactoryResolver], (resolver: ComponentFactoryResolver) => {
expect(resolver.resolveComponentFactory(CompUsingModuleDirectiveAndPipe).componentType)
.toBe(CompUsingModuleDirectiveAndPipe);
}));
});
describe('per test modules', () => {
it('should use set up providers',
withModule(() => moduleConfig).inject([FancyService], (service: FancyService) => {
expect(service.value).toEqual('real value');
}));
it('should use set up directives and pipes',
withModule(() => moduleConfig)
.inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
let compFixture = tcb.createSync(CompUsingModuleDirectiveAndPipe);
let el = compFixture.debugElement;
compFixture.detectChanges();
expect(el.children[0].properties['title']).toBe('transformed someValue');
}));
it('should use set up nested modules',
withModule(() => moduleConfig)
.inject([SomeNestedModule], (nestedModule: SomeNestedModule) => {
expect(nestedModule).toBeAnInstanceOf(SomeNestedModule);
}));
it('should use set up precompile components',
withModule(() => moduleConfig)
.inject([ComponentFactoryResolver], (resolver: ComponentFactoryResolver) => {
expect(
resolver.resolveComponentFactory(CompUsingModuleDirectiveAndPipe).componentType)
.toBe(CompUsingModuleDirectiveAndPipe);
}));
});
describe('precompile components with template url', () => {
let xhrGet: jasmine.Spy;
beforeEach(() => {
xhrGet = jasmine.createSpy('xhrGet').and.returnValue(Promise.resolve('Hello world!'));
configureCompiler({providers: [{provide: XHR, useValue: {get: xhrGet}}]});
});
it('should allow to precompile components with templateUrl using the async helper',
async(withModule(() => {
return {precompile: [CompWithUrlTemplate]};
}).inject([ComponentFactoryResolver], (resolver: ComponentFactoryResolver) => {
expect(resolver.resolveComponentFactory(CompWithUrlTemplate).componentType)
.toBe(CompWithUrlTemplate);
})));
it('should allow to precompile components with templateUrl using the fakeAsync helper',
fakeAsync(withModule(() => {
return {precompile: [CompWithUrlTemplate]};
}).inject([ComponentFactoryResolver], (resolver: ComponentFactoryResolver) => {
expect(resolver.resolveComponentFactory(CompWithUrlTemplate).componentType)
.toBe(CompWithUrlTemplate);
})));
});
describe('setting up the compiler', () => {
describe('providers', () => {
beforeEach(() => {
let xhrGet = jasmine.createSpy('xhrGet').and.returnValue(Promise.resolve('Hello world!'));
configureCompiler({providers: [{provide: XHR, useValue: {get: xhrGet}}]});
});
it('should use set up providers',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
let compFixture = tcb.createFakeAsync(CompWithUrlTemplate);
expect(compFixture.nativeElement).toHaveText('Hello world!');
})));
});
describe('useJit true', () => {
beforeEach(() => { configureCompiler({useJit: true}); });
it('should set the value into CompilerConfig',
inject([CompilerConfig], (config: CompilerConfig) => {
expect(config.useJit).toBe(true);
}));
});
describe('useJit false', () => {
beforeEach(() => { configureCompiler({useJit: false}); });
it('should set the value into CompilerConfig',
inject([CompilerConfig], (config: CompilerConfig) => {
expect(config.useJit).toBe(false);
}));
});
});
});
describe('errors', () => { describe('errors', () => {
var originalJasmineIt: any; var originalJasmineIt: any;
var originalJasmineBeforeEach: any; var originalJasmineBeforeEach: any;
@ -294,6 +447,36 @@ export function main() {
}); });
}); });
}); });
describe('precompile', () => {
let xhrGet: jasmine.Spy;
beforeEach(() => {
xhrGet = jasmine.createSpy('xhrGet').and.returnValue(Promise.resolve('Hello world!'));
configureCompiler({providers: [{provide: XHR, useValue: {get: xhrGet}}]});
});
it('should report an error for precompile components with templateUrl and sync tests', () => {
var itPromise = patchJasmineIt();
expect(
() => it(
'should fail',
withModule(() => { return {precompile: [CompWithUrlTemplate]}; })
.inject(
[ComponentFactoryResolver],
(resolver: ComponentFactoryResolver) => {
expect(
resolver.resolveComponentFactory(CompWithUrlTemplate).componentType)
.toBe(CompWithUrlTemplate);
})))
.toThrowError(
`This test module precompiles the component ${stringify(CompWithUrlTemplate)} which is using a "templateUrl", but the test is synchronous. ` +
'Please use the "async(...)" or "fakeAsync(...)" helper functions to make the test asynchronous.');
restoreJasmineIt();
});
});
}); });
describe('test component builder', function() { describe('test component builder', function() {

View File

@ -8,10 +8,10 @@
import {inject, ddescribe, describe, it, iit, expect, beforeEach, beforeEachProviders,} from '@angular/core/testing/testing_internal'; import {inject, ddescribe, describe, it, iit, expect, beforeEach, beforeEachProviders,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {TestInjector} from '@angular/core/testing'; import {TestInjector, configureModule} from '@angular/core/testing';
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {provide, Injector, ViewMetadata, Component, Injectable, ComponentRef} from '@angular/core'; import {provide, Injector, ViewMetadata, Component, Injectable, ComponentRef, ReflectiveInjector, getPlatform} from '@angular/core';
import {NgIf} from '@angular/common'; import {NgIf} from '@angular/common';
import {WebWorkerRootRenderer} from '@angular/platform-browser/src/web_workers/worker/renderer'; import {WebWorkerRootRenderer} from '@angular/platform-browser/src/web_workers/worker/renderer';
import {ClientMessageBrokerFactory, ClientMessageBrokerFactory_} from '@angular/platform-browser/src/web_workers/shared/client_message_broker'; import {ClientMessageBrokerFactory, ClientMessageBrokerFactory_} from '@angular/platform-browser/src/web_workers/shared/client_message_broker';
@ -25,7 +25,8 @@ import {createPairedMessageBuses, PairedMessageBuses} from '../shared/web_worker
import {ServiceMessageBrokerFactory_} from '@angular/platform-browser/src/web_workers/shared/service_message_broker'; import {ServiceMessageBrokerFactory_} from '@angular/platform-browser/src/web_workers/shared/service_message_broker';
import {CompilerConfig} from '@angular/compiler'; import {CompilerConfig} from '@angular/compiler';
import {dispatchEvent} from '../../../../platform-browser/testing/browser_util'; import {dispatchEvent} from '../../../../platform-browser/testing/browser_util';
import {TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS} from '@angular/platform-browser/testing'; import {BrowserTestModule} from '@angular/platform-browser/testing';
import {browserTestCompiler, browserDynamicTestPlatform} from '@angular/platform-browser-dynamic/testing'
export function main() { export function main() {
function createWebWorkerBrokerFactory( function createWebWorkerBrokerFactory(
@ -58,199 +59,206 @@ export function main() {
return new DebugDomRootRenderer(workerRootRenderer); return new DebugDomRootRenderer(workerRootRenderer);
} }
describe('Web Worker Renderer', () => { describe(
var uiInjector: Injector; 'Web Worker Renderer',
var uiRenderStore: RenderStore; () => {
var workerRenderStore: RenderStore; var uiInjector: Injector;
var uiRenderStore: RenderStore;
var workerRenderStore: RenderStore;
beforeEachProviders(() => { beforeEach(() => {
uiRenderStore = new RenderStore(); uiRenderStore = new RenderStore();
var testUiInjector = new TestInjector(); var testUiInjector = new TestInjector();
testUiInjector.platformProviders = TEST_BROWSER_PLATFORM_PROVIDERS; testUiInjector.platform = browserDynamicTestPlatform();
testUiInjector.applicationProviders = TEST_BROWSER_APPLICATION_PROVIDERS; testUiInjector.compilerFactory = browserTestCompiler;
testUiInjector.addProviders([ testUiInjector.appModule = BrowserTestModule;
Serializer, {provide: RenderStore, useValue: uiRenderStore}, testUiInjector.configureModule({
{provide: DomRootRenderer, useClass: DomRootRenderer_}, providers: [
{provide: RootRenderer, useExisting: DomRootRenderer} Serializer, {provide: RenderStore, useValue: uiRenderStore},
]); {provide: DomRootRenderer, useClass: DomRootRenderer_},
uiInjector = testUiInjector.createInjector(); {provide: RootRenderer, useExisting: DomRootRenderer}
var uiSerializer = uiInjector.get(Serializer); ]
var domRootRenderer = uiInjector.get(DomRootRenderer); });
workerRenderStore = new RenderStore(); uiInjector = testUiInjector.createInjectorSync();
return [ var uiSerializer = uiInjector.get(Serializer);
Serializer, {provide: CompilerConfig, useValue: new CompilerConfig({genDebugInfo: true})}, var domRootRenderer = uiInjector.get(DomRootRenderer);
{provide: RenderStore, useValue: workerRenderStore}, { workerRenderStore = new RenderStore();
provide: RootRenderer,
useFactory: (workerSerializer: Serializer) => { configureModule({
return createWorkerRenderer( providers: [
workerSerializer, uiSerializer, domRootRenderer, uiRenderStore, workerRenderStore); Serializer, {provide: RenderStore, useValue: workerRenderStore}, {
}, provide: RootRenderer,
deps: [Serializer] useFactory: (workerSerializer: Serializer) => {
return createWorkerRenderer(
workerSerializer, uiSerializer, domRootRenderer, uiRenderStore,
workerRenderStore);
},
deps: [Serializer]
}
]
});
});
function getRenderElement(workerEl: any) {
var id = workerRenderStore.serialize(workerEl);
return uiRenderStore.deserialize(id);
} }
];
});
function getRenderElement(workerEl: any) { function getRenderer(componentRef: ComponentRef<any>) {
var id = workerRenderStore.serialize(workerEl); return (<any>componentRef.hostView).internalView.renderer;
return uiRenderStore.deserialize(id); }
}
function getRenderer(componentRef: ComponentRef<any>) { it('should update text nodes',
return (<any>componentRef.hostView).internalView.renderer; inject(
} [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideView(MyComp2, new ViewMetadata({template: '<div>{{ctxProp}}</div>'}))
.createAsync(MyComp2)
.then((fixture) => {
var renderEl = getRenderElement(fixture.debugElement.nativeElement);
expect(renderEl).toHaveText('');
it('should update text nodes', fixture.debugElement.componentInstance.ctxProp = 'Hello World!';
inject( fixture.detectChanges();
[TestComponentBuilder, AsyncTestCompleter], expect(renderEl).toHaveText('Hello World!');
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { async.done();
tcb.overrideView(MyComp2, new ViewMetadata({template: '<div>{{ctxProp}}</div>'}))
.createAsync(MyComp2)
.then((fixture) => {
var renderEl = getRenderElement(fixture.debugElement.nativeElement);
expect(renderEl).toHaveText('');
fixture.debugElement.componentInstance.ctxProp = 'Hello World!'; });
fixture.detectChanges(); }));
expect(renderEl).toHaveText('Hello World!');
async.done();
}); it('should update any element property/attributes/class/style(s) independent of the compilation on the root element and other elements',
})); inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideView(
MyComp2, new ViewMetadata(
{template: '<input [title]="y" style="position:absolute">'}))
.createAsync(MyComp2)
.then((fixture) => {
var checkSetters =
(componentRef: any /** TODO #9100 */,
workerEl: any /** TODO #9100 */) => {
var renderer = getRenderer(componentRef);
var el = getRenderElement(workerEl);
renderer.setElementProperty(workerEl, 'tabIndex', 1);
expect((<HTMLInputElement>el).tabIndex).toEqual(1);
it('should update any element property/attributes/class/style(s) independent of the compilation on the root element and other elements', renderer.setElementClass(workerEl, 'a', true);
inject( expect(getDOM().hasClass(el, 'a')).toBe(true);
[TestComponentBuilder, AsyncTestCompleter], renderer.setElementClass(workerEl, 'a', false);
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { expect(getDOM().hasClass(el, 'a')).toBe(false);
tcb.overrideView(
MyComp2,
new ViewMetadata({template: '<input [title]="y" style="position:absolute">'}))
.createAsync(MyComp2)
.then((fixture) => {
var checkSetters =
(componentRef: any /** TODO #9100 */, workerEl: any /** TODO #9100 */) => {
var renderer = getRenderer(componentRef);
var el = getRenderElement(workerEl);
renderer.setElementProperty(workerEl, 'tabIndex', 1);
expect((<HTMLInputElement>el).tabIndex).toEqual(1);
renderer.setElementClass(workerEl, 'a', true); renderer.setElementStyle(workerEl, 'width', '10px');
expect(getDOM().hasClass(el, 'a')).toBe(true); expect(getDOM().getStyle(el, 'width')).toEqual('10px');
renderer.setElementClass(workerEl, 'a', false); renderer.setElementStyle(workerEl, 'width', null);
expect(getDOM().hasClass(el, 'a')).toBe(false); expect(getDOM().getStyle(el, 'width')).toEqual('');
renderer.setElementStyle(workerEl, 'width', '10px'); renderer.setElementAttribute(workerEl, 'someattr', 'someValue');
expect(getDOM().getStyle(el, 'width')).toEqual('10px'); expect(getDOM().getAttribute(el, 'someattr')).toEqual('someValue');
renderer.setElementStyle(workerEl, 'width', null); };
expect(getDOM().getStyle(el, 'width')).toEqual('');
renderer.setElementAttribute(workerEl, 'someattr', 'someValue'); // root element
expect(getDOM().getAttribute(el, 'someattr')).toEqual('someValue'); checkSetters(fixture.componentRef, fixture.debugElement.nativeElement);
}; // nested elements
checkSetters(
fixture.componentRef, fixture.debugElement.children[0].nativeElement);
// root element async.done();
checkSetters(fixture.componentRef, fixture.debugElement.nativeElement); });
// nested elements }));
checkSetters(
fixture.componentRef, fixture.debugElement.children[0].nativeElement);
async.done(); it('should update any template comment property/attributes',
}); inject(
})); [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var tpl = '<template [ngIf]="ctxBoolProp"></template>';
tcb.overrideView(MyComp2, new ViewMetadata({template: tpl, directives: [NgIf]}))
it('should update any template comment property/attributes', .createAsync(MyComp2)
inject( .then((fixture) => {
[TestComponentBuilder, AsyncTestCompleter], (<MyComp2>fixture.debugElement.componentInstance).ctxBoolProp = true;
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { fixture.detectChanges();
var tpl = '<template [ngIf]="ctxBoolProp"></template>'; var el = getRenderElement(fixture.debugElement.nativeElement);
tcb.overrideView(MyComp2, new ViewMetadata({template: tpl, directives: [NgIf]})) expect(getDOM().getInnerHTML(el)).toContain('"ng-reflect-ng-if": "true"');
async.done();
});
}));
.createAsync(MyComp2) it('should add and remove fragments',
.then((fixture) => { inject(
(<MyComp2>fixture.debugElement.componentInstance).ctxBoolProp = true; [TestComponentBuilder, AsyncTestCompleter],
fixture.detectChanges(); (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var el = getRenderElement(fixture.debugElement.nativeElement); tcb.overrideView(MyComp2, new ViewMetadata({
expect(getDOM().getInnerHTML(el)).toContain('"ng-reflect-ng-if": "true"'); template: '<template [ngIf]="ctxBoolProp">hello</template>',
async.done(); directives: [NgIf]
}); }))
})); .createAsync(MyComp2)
.then((fixture) => {
it('should add and remove fragments', var rootEl = getRenderElement(fixture.debugElement.nativeElement);
inject( expect(rootEl).toHaveText('');
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideView(MyComp2, new ViewMetadata({
template: '<template [ngIf]="ctxBoolProp">hello</template>',
directives: [NgIf]
}))
.createAsync(MyComp2)
.then((fixture) => {
var rootEl = getRenderElement(fixture.debugElement.nativeElement); fixture.debugElement.componentInstance.ctxBoolProp = true;
expect(rootEl).toHaveText(''); fixture.detectChanges();
expect(rootEl).toHaveText('hello');
fixture.debugElement.componentInstance.ctxBoolProp = true; fixture.debugElement.componentInstance.ctxBoolProp = false;
fixture.detectChanges(); fixture.detectChanges();
expect(rootEl).toHaveText('hello'); expect(rootEl).toHaveText('');
fixture.debugElement.componentInstance.ctxBoolProp = false; async.done();
fixture.detectChanges(); });
expect(rootEl).toHaveText(''); }));
async.done(); if (getDOM().supportsDOMEvents()) {
}); it('should call actions on the element',
})); inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideView(MyComp2, new ViewMetadata({template: '<input [title]="y">'}))
.createAsync(MyComp2)
.then((fixture) => {
var el = fixture.debugElement.children[0];
getRenderer(fixture.componentRef)
.invokeElementMethod(el.nativeElement, 'setAttribute', ['a', 'b']);
if (getDOM().supportsDOMEvents()) { expect(getDOM().getAttribute(getRenderElement(el.nativeElement), 'a'))
it('should call actions on the element', .toEqual('b');
inject( async.done();
[TestComponentBuilder, AsyncTestCompleter], });
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { }));
tcb.overrideView(MyComp2, new ViewMetadata({template: '<input [title]="y">'}))
.createAsync(MyComp2)
.then((fixture) => {
var el = fixture.debugElement.children[0];
getRenderer(fixture.componentRef)
.invokeElementMethod(el.nativeElement, 'setAttribute', ['a', 'b']);
expect(getDOM().getAttribute(getRenderElement(el.nativeElement), 'a')) it('should listen to events',
.toEqual('b'); inject(
async.done(); [TestComponentBuilder, AsyncTestCompleter],
}); (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
})); tcb.overrideView(
MyComp2,
new ViewMetadata({template: '<input (change)="ctxNumProp = 1">'}))
.createAsync(MyComp2)
.then((fixture) => {
var el = fixture.debugElement.children[0];
dispatchEvent(getRenderElement(el.nativeElement), 'change');
expect(fixture.componentInstance.ctxNumProp).toBe(1);
it('should listen to events', fixture.destroy();
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideView(
MyComp2, new ViewMetadata({template: '<input (change)="ctxNumProp = 1">'}))
.createAsync(MyComp2)
.then((fixture) => {
var el = fixture.debugElement.children[0];
dispatchEvent(getRenderElement(el.nativeElement), 'change');
expect(fixture.componentInstance.ctxNumProp).toBe(1);
fixture.destroy(); async.done();
});
async.done(); }));
}); }
})); });
}
});
} }
@Component({selector: 'my-comp', directives: []}) @Component(
@Injectable() {selector: 'my-comp',
class MyComp2 { directives: []}) @Injectable() class MyComp2 {
ctxProp: string; ctxProp: string; ctxNumProp: any /** TODO #9100 */; ctxBoolProp: boolean; constructor() {
ctxNumProp: any /** TODO #9100 */;
ctxBoolProp: boolean;
constructor() {
this.ctxProp = 'initial value'; this.ctxProp = 'initial value';
this.ctxNumProp = 0; this.ctxNumProp = 0;
this.ctxBoolProp = false; this.ctxBoolProp = false;
} }
throwError() { throw 'boom'; } throwError() { throw 'boom';}
} }

View File

@ -7,31 +7,16 @@
*/ */
import {LocationStrategy} from '@angular/common'; import {LocationStrategy} from '@angular/common';
import {APP_ID, NgZone, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER} from '@angular/core'; import {APP_ID, AppModule, NgZone, OpaqueToken, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER, PlatformRef, ReflectiveInjector, assertPlatform, createPlatform, getPlatform} from '@angular/core';
import {BROWSER_APP_PROVIDERS} from '../src/browser'; import {BROWSER_APP_PROVIDERS, BrowserModule} from '../src/browser';
import {BrowserDomAdapter} from '../src/browser/browser_adapter'; import {BrowserDomAdapter} from '../src/browser/browser_adapter';
import {AnimationDriver} from '../src/dom/animation_driver'; import {AnimationDriver} from '../src/dom/animation_driver';
import {ELEMENT_PROBE_PROVIDERS} from '../src/dom/debug/ng_probe'; import {ELEMENT_PROBE_PROVIDERS} from '../src/dom/debug/ng_probe';
import {BrowserDetection} from './browser_util'; import {BrowserDetection} from './browser_util';
const BROWSER_TEST_PLATFORM_MARKER = new OpaqueToken('BrowserTestPlatformMarker');
/**
* Default platform providers for testing without a compiler.
*/
const TEST_BROWSER_STATIC_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> = [
PLATFORM_COMMON_PROVIDERS,
{provide: PLATFORM_INITIALIZER, useValue: initBrowserTests, multi: true}
];
const ADDITIONAL_TEST_BROWSER_STATIC_PROVIDERS: Array<any /*Type | Provider | any[]*/> = [
{provide: APP_ID, useValue: 'a'}, ELEMENT_PROBE_PROVIDERS,
{provide: NgZone, useFactory: createNgZone},
{provide: AnimationDriver, useValue: AnimationDriver.NOOP}
];
function initBrowserTests() { function initBrowserTests() {
BrowserDomAdapter.makeCurrent(); BrowserDomAdapter.makeCurrent();
@ -42,19 +27,35 @@ function createNgZone(): NgZone {
return new NgZone({enableLongStackTrace: true}); return new NgZone({enableLongStackTrace: true});
} }
const TEST_BROWSER_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> = [
PLATFORM_COMMON_PROVIDERS, {provide: BROWSER_TEST_PLATFORM_MARKER, useValue: true},
{provide: PLATFORM_INITIALIZER, useValue: initBrowserTests, multi: true}
];
/** /**
* Default platform providers for testing. * Platform for testing
*
* @experimental API related to bootstrapping are still under review.
*/
export function browserTestPlatform(): PlatformRef {
if (!getPlatform()) {
createPlatform(ReflectiveInjector.resolveAndCreate(TEST_BROWSER_PLATFORM_PROVIDERS));
}
return assertPlatform(BROWSER_TEST_PLATFORM_MARKER);
}
/**
* AppModule for testing.
* *
* @stable * @stable
*/ */
export const TEST_BROWSER_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> = @AppModule({
TEST_BROWSER_STATIC_PLATFORM_PROVIDERS; modules: [BrowserModule],
providers: [
/** {provide: APP_ID, useValue: 'a'}, ELEMENT_PROBE_PROVIDERS,
* Default application providers for testing without a compiler. {provide: NgZone, useFactory: createNgZone},
* {provide: AnimationDriver, useValue: AnimationDriver.NOOP}
* @stable ]
*/ })
export const TEST_BROWSER_APPLICATION_PROVIDERS: Array<any /*Type | Provider | any[]*/> = export class BrowserTestModule {
[BROWSER_APP_PROVIDERS, ADDITIONAL_TEST_BROWSER_STATIC_PROVIDERS]; }

View File

@ -26,6 +26,7 @@ export function main() {
describe('platform-server integration', () => { describe('platform-server integration', () => {
beforeEach(() => disposePlatform());
afterEach(() => disposePlatform()); afterEach(() => disposePlatform());
it('should bootstrap', async(() => { it('should bootstrap', async(() => {

View File

@ -6,76 +6,48 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {COMPILER_PROVIDERS, DirectiveResolver, ViewResolver, XHR} from '@angular/compiler'; import {AppModule, OpaqueToken, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER, PlatformRef, ReflectiveInjector, assertPlatform, createPlatform, getPlatform} from '@angular/core';
import {MockDirectiveResolver, MockViewResolver, OverridingTestComponentBuilder} from '@angular/compiler/testing'; import {BrowserDynamicTestModule, browserTestCompiler} from '@angular/platform-browser-dynamic/testing';
import {APPLICATION_COMMON_PROVIDERS, APP_ID, NgZone, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER, RootRenderer} from '@angular/core';
import {TestComponentBuilder, TestComponentRenderer} from '@angular/core/testing';
import {AnimationDriver, BROWSER_SANITIZATION_PROVIDERS, DOCUMENT, EVENT_MANAGER_PLUGINS, EventManager} from '@angular/platform-browser';
import {DOMTestComponentRenderer} from '../platform_browser_dynamic_testing_private';
import {DomEventsPlugin, DomRootRenderer, DomRootRenderer_, DomSharedStylesHost, ELEMENT_PROBE_PROVIDERS, SharedStylesHost, getDOM} from '../platform_browser_private';
import {Parse5DomAdapter} from '../src/parse5_adapter'; import {Parse5DomAdapter} from '../src/parse5_adapter';
const SERVER_TEST_PLATFORM_MARKER = new OpaqueToken('ServerTestPlatformMarker');
function initServerTests() { function initServerTests() {
Parse5DomAdapter.makeCurrent(); Parse5DomAdapter.makeCurrent();
} }
/** /**
* Default platform providers for testing. * Creates a compiler for testing
* *
* @experimental * @stable
*/ */
export const TEST_SERVER_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> = export const serverTestCompiler = browserTestCompiler;
const TEST_SERVER_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> =
/*@ts2dart_const*/[ /*@ts2dart_const*/[
PLATFORM_COMMON_PROVIDERS, PLATFORM_COMMON_PROVIDERS,
/*@ts2dart_Provider*/ { /*@ts2dart_Provider*/ {provide: PLATFORM_INITIALIZER, useValue: initServerTests, multi: true},
provide: PLATFORM_INITIALIZER, {provide: SERVER_TEST_PLATFORM_MARKER, useValue: true}
useValue: initServerTests,
multi: true
}
]; ];
function appDoc() {
try {
return getDOM().defaultDoc();
} catch (e) {
return null;
}
}
function createNgZone(): NgZone {
return new NgZone({enableLongStackTrace: true});
}
/** /**
* Default application providers for testing. * Platform for testing
* *
* @experimental * @experimental API related to bootstrapping are still under review.
*/ */
export const TEST_SERVER_APPLICATION_PROVIDERS: Array<any /*Type | Provider | any[]*/> = export function serverTestPlatform(): PlatformRef {
/*@ts2dart_const*/[ if (!getPlatform()) {
// TODO(julie: when angular2/platform/server is available, use that instead of making our own createPlatform(ReflectiveInjector.resolveAndCreate(TEST_SERVER_PLATFORM_PROVIDERS));
// list here. }
APPLICATION_COMMON_PROVIDERS, COMPILER_PROVIDERS, BROWSER_SANITIZATION_PROVIDERS, return assertPlatform(SERVER_TEST_PLATFORM_MARKER);
/* @ts2dart_Provider */ {provide: DOCUMENT, useFactory: appDoc}, }
/* @ts2dart_Provider */ {provide: DomRootRenderer, useClass: DomRootRenderer_},
/* @ts2dart_Provider */ {provide: RootRenderer, useExisting: DomRootRenderer}, /**
/* @ts2dart_Provider */ {provide: AnimationDriver, useValue: AnimationDriver.NOOP}, * AppModule for testing.
EventManager, *
/* @ts2dart_Provider */ { * @stable
provide: EVENT_MANAGER_PLUGINS, */
useClass: DomEventsPlugin, @AppModule({modules: [BrowserDynamicTestModule]})
multi: true export class ServerTestModule {
}, }
/* @ts2dart_Provider */ {provide: XHR, useClass: XHR},
/* @ts2dart_Provider */ {provide: APP_ID, useValue: 'a'},
/* @ts2dart_Provider */ {provide: SharedStylesHost, useExisting: DomSharedStylesHost},
DomSharedStylesHost, ELEMENT_PROBE_PROVIDERS,
{provide: TestComponentBuilder, useClass: OverridingTestComponentBuilder},
/* @ts2dart_Provider */ {provide: DirectiveResolver, useClass: MockDirectiveResolver},
/* @ts2dart_Provider */ {provide: ViewResolver, useClass: MockViewResolver},
/* @ts2dart_Provider */ {provide: TestComponentRenderer, useClass: DOMTestComponentRenderer},
/* @ts2dart_Provider */ {provide: NgZone, useFactory: createNgZone}
];

View File

@ -9,6 +9,7 @@
import {APP_BASE_HREF, LocationStrategy} from '@angular/common'; import {APP_BASE_HREF, LocationStrategy} from '@angular/common';
import {MockLocationStrategy} from '@angular/common/testing/mock_location_strategy'; import {MockLocationStrategy} from '@angular/common/testing/mock_location_strategy';
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {disposePlatform} from '@angular/core';
import {ApplicationRef} from '@angular/core/src/application_ref'; import {ApplicationRef} from '@angular/core/src/application_ref';
import {Console} from '@angular/core/src/console'; import {Console} from '@angular/core/src/console';
import {Component} from '@angular/core/src/metadata'; import {Component} from '@angular/core/src/metadata';
@ -39,6 +40,9 @@ export function main() {
useClass: MockApplicationRef useClass: MockApplicationRef
}]); }]);
beforeEach(() => disposePlatform());
afterEach(() => disposePlatform());
// do not refactor out the `bootstrap` functionality. We still want to // do not refactor out the `bootstrap` functionality. We still want to
// keep this test around so we can ensure that bootstrap a router works // keep this test around so we can ensure that bootstrap a router works
it('should bootstrap a simple app', it('should bootstrap a simple app',

View File

@ -13,7 +13,7 @@ import {APP_BASE_HREF, LocationStrategy} from '@angular/common';
import {Component, Directive} from '@angular/core/src/metadata'; import {Component, Directive} from '@angular/core/src/metadata';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {Console} from '@angular/core/src/console'; import {Console} from '@angular/core/src/console';
import {provide} from '@angular/core'; import {provide, disposePlatform} from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens'; import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {ROUTER_PROVIDERS, Router, RouteConfig, ROUTER_DIRECTIVES} from '@angular/router-deprecated'; import {ROUTER_PROVIDERS, Router, RouteConfig, ROUTER_DIRECTIVES} from '@angular/router-deprecated';
@ -38,6 +38,7 @@ export function main() {
var fakeDoc: any /** TODO #9100 */, el: any /** TODO #9100 */, var fakeDoc: any /** TODO #9100 */, el: any /** TODO #9100 */,
testBindings: any /** TODO #9100 */; testBindings: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
disposePlatform();
fakeDoc = getDOM().createHtmlDocument(); fakeDoc = getDOM().createHtmlDocument();
el = getDOM().createElement('app-cmp', fakeDoc); el = getDOM().createElement('app-cmp', fakeDoc);
getDOM().appendChild(fakeDoc.body, el); getDOM().appendChild(fakeDoc.body, el);
@ -51,6 +52,8 @@ export function main() {
]; ];
}); });
afterEach(() => disposePlatform());
it('should bootstrap an app with a hierarchy', it('should bootstrap an app with a hierarchy',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
bootstrap(HierarchyAppCmp, testBindings).then((applicationRef) => { bootstrap(HierarchyAppCmp, testBindings).then((applicationRef) => {

View File

@ -72,8 +72,10 @@ Promise.all([
var testing = providers[0]; var testing = providers[0];
var testingBrowser = providers[1]; var testingBrowser = providers[1];
testing.setBaseTestProviders(testingBrowser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, testing.initTestEnvironment(
testingBrowser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS); testingBrowser.browserTestCompiler,
testingBrowser.browserDynamicTestPlatform(),
testingBrowser.BrowserDynamicTestModule);
}).then(function() { }).then(function() {
// Finally, load all spec files. // Finally, load all spec files.

View File

@ -6,13 +6,16 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Class, Component, EventEmitter, Testability, provide} from '@angular/core'; import {Class, Component, EventEmitter, Testability, disposePlatform, provide} from '@angular/core';
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, iit, inject, it} from '@angular/core/testing/testing_internal';
import {UpgradeAdapter} from '@angular/upgrade'; import {UpgradeAdapter} from '@angular/upgrade';
import * as angular from '@angular/upgrade/src/angular_js'; import * as angular from '@angular/upgrade/src/angular_js';
export function main() { export function main() {
describe('adapter: ng1 to ng2', () => { describe('adapter: ng1 to ng2', () => {
beforeEach(() => disposePlatform());
afterEach(() => disposePlatform());
it('should have angular 1 loaded', () => expect(angular.version.major).toBe(1)); it('should have angular 1 loaded', () => expect(angular.version.major).toBe(1));
it('should instantiate ng2 in ng1 template and project content', it('should instantiate ng2 in ng1 template and project content',

View File

@ -74,11 +74,11 @@ System.config({
System.import('@angular/core/testing') System.import('@angular/core/testing')
.then(function(coreTesting){ .then(function(coreTesting){
return System.import('@angular/platform-browser-dynamic/testing') return System.import('@angular/platform-browser-dynamic/testing')
.then(function(browserTesting){ .then(function(browserTesting) {
coreTesting.setBaseTestProviders( coreTesting.initTestEnvironment(
browserTesting.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, browserTesting.browserTestCompiler,
browserTesting.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS browserTesting.browserDynamicTestPlatform(),
); browserTesting.BrowserDynamicTestModule);
}); });
}) })
.then(function() { .then(function() {

View File

@ -1,6 +1,6 @@
var testingPlatformServer = require('../../all/@angular/platform-server/testing/server.js'); var testingPlatformServer = require('../../all/@angular/platform-server/testing/server.js');
var testing = require('../../all/@angular/core/testing'); var testing = require('../../all/@angular/core/testing');
testing.setBaseTestProviders( testing.initTestEnvironment(
testingPlatformServer.TEST_SERVER_PLATFORM_PROVIDERS, testingPlatformServer.serverTestCompiler, testingPlatformServer.serverTestPlatform(),
testingPlatformServer.TEST_SERVER_APPLICATION_PROVIDERS); testingPlatformServer.ServerTestModule);

View File

@ -290,6 +290,7 @@ export declare class CollectionChangeRecord {
/** @stable */ /** @stable */
export declare class Compiler { export declare class Compiler {
injector: Injector;
clearCache(): void; clearCache(): void;
clearCacheFor(type: Type): void; clearCacheFor(type: Type): void;
compileAppModuleAsync<T>(moduleType: ConcreteType<T>, metadata?: AppModuleMetadata): Promise<AppModuleFactory<T>>; compileAppModuleAsync<T>(moduleType: ConcreteType<T>, metadata?: AppModuleMetadata): Promise<AppModuleFactory<T>>;
@ -451,6 +452,12 @@ export declare abstract class ComponentResolver {
abstract resolveComponent(component: Type | string): Promise<ComponentFactory<any>>; abstract resolveComponent(component: Type | string): Promise<ComponentFactory<any>>;
} }
/** @stable */
export declare class ComponentStillLoadingError extends BaseException {
compType: Type;
constructor(compType: Type);
}
/** @stable */ /** @stable */
export declare var ContentChild: ContentChildMetadataFactory; export declare var ContentChild: ContentChildMetadataFactory;

View File

@ -37,6 +37,21 @@ export declare var ComponentFixtureAutoDetect: OpaqueToken;
/** @experimental */ /** @experimental */
export declare var ComponentFixtureNoNgZone: OpaqueToken; export declare var ComponentFixtureNoNgZone: OpaqueToken;
/** @stable */
export declare function configureCompiler(config: {
providers?: any[];
useJit?: boolean;
}): void;
/** @stable */
export declare function configureModule(moduleDef: {
providers?: any[];
directives?: any[];
pipes?: any[];
precompile?: any[];
modules?: any[];
}): void;
/** @deprecated */ /** @deprecated */
export declare var ddescribe: any; export declare var ddescribe: any;
@ -67,12 +82,21 @@ export declare function getTestInjector(): TestInjector;
/** @deprecated */ /** @deprecated */
export declare var iit: any; export declare var iit: any;
/** @experimental */
export declare function initTestEnvironment(compilerFactory: TestCompilerFactory, platform: PlatformRef, appModule: Type): void;
/** @stable */ /** @stable */
export declare function inject(tokens: any[], fn: Function): () => any; export declare function inject(tokens: any[], fn: Function): () => any;
/** @experimental */ /** @experimental */
export declare class InjectSetupWrapper { export declare class InjectSetupWrapper {
constructor(_providers: () => any); constructor(_moduleDef: () => {
providers?: any[];
directives?: any[];
pipes?: any[];
precompile?: any[];
modules?: any[];
});
inject(tokens: any[], fn: Function): () => any; inject(tokens: any[], fn: Function): () => any;
} }
@ -80,10 +104,13 @@ export declare class InjectSetupWrapper {
export declare var it: any; export declare var it: any;
/** @experimental */ /** @experimental */
export declare function resetBaseTestProviders(): void; export declare function resetTestEnvironment(): void;
/** @experimental */ /** @experimental */
export declare function setBaseTestProviders(platformProviders: Array<Type | Provider | any[]>, applicationProviders: Array<Type | Provider | any[]>): void; export declare type TestCompilerFactory = (config: {
providers?: Array<Type | Provider | any[]>;
useJit?: boolean;
}) => Compiler;
/** @stable */ /** @stable */
export declare class TestComponentBuilder { export declare class TestComponentBuilder {
@ -107,19 +134,40 @@ export declare class TestComponentRenderer {
} }
/** @experimental */ /** @experimental */
export declare class TestInjector { export declare class TestInjector implements Injector {
applicationProviders: Array<Type | Provider | any[] | any>; appModule: Type;
platformProviders: Array<Type | Provider | any[] | any>; compilerFactory: TestCompilerFactory;
addProviders(providers: Array<Type | Provider | any[] | any>): void; platform: PlatformRef;
createInjector(): ReflectiveInjector; configureCompiler(config: {
providers?: any[];
useJit?: boolean;
}): void;
configureModule(moduleDef: {
providers?: any[];
directives?: any[];
pipes?: any[];
precompile?: any[];
modules?: any[];
}): void;
createInjectorAsync(): Promise<Injector>;
createInjectorSync(): Injector;
execute(tokens: any[], fn: Function): any; execute(tokens: any[], fn: Function): any;
get(token: any): any; get(token: any, notFoundValue?: any): any;
reset(): void; reset(): void;
} }
/** @experimental */ /** @experimental */
export declare function tick(millis?: number): void; export declare function tick(millis?: number): void;
/** @experimental */
export declare function withModule(moduleDef: () => {
providers?: any[];
directives?: any[];
pipes?: any[];
precompile?: any[];
modules?: any[];
}): InjectSetupWrapper;
/** @experimental */ /** @experimental */
export declare function withProviders(providers: () => any): InjectSetupWrapper; export declare function withProviders(providers: () => any): InjectSetupWrapper;

View File

@ -1,5 +1,12 @@
/** @stable */ /** @stable */
export declare const TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS: Array<any>; export declare class BrowserDynamicTestModule {
}
/** @experimental */
export declare const browserDynamicTestPlatform: typeof browserTestPlatform;
/** @stable */ /** @stable */
export declare const TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS: Array<any>; export declare function browserTestCompiler({providers, useJit}?: {
providers?: Array<Type | Provider | any[]>;
useJit?: boolean;
}): Compiler;

View File

@ -1,5 +1,6 @@
/** @stable */ /** @stable */
export declare const TEST_BROWSER_APPLICATION_PROVIDERS: Array<any>; export declare class BrowserTestModule {
}
/** @stable */ /** @experimental */
export declare const TEST_BROWSER_PLATFORM_PROVIDERS: Array<any>; export declare function browserTestPlatform(): PlatformRef;

View File

@ -1,5 +1,9 @@
/** @experimental */ /** @stable */
export declare const TEST_SERVER_APPLICATION_PROVIDERS: Array<any>; export declare const serverTestCompiler: typeof browserTestCompiler;
/** @stable */
export declare class ServerTestModule {
}
/** @experimental */ /** @experimental */
export declare const TEST_SERVER_PLATFORM_PROVIDERS: Array<any>; export declare function serverTestPlatform(): PlatformRef;