fix(compiler): Update types for TypeScript nullability support

This commit is contained in:
Miško Hevery
2017-03-24 09:59:58 -07:00
committed by Hans
parent d8b73e4223
commit 09d9f5fe54
118 changed files with 2086 additions and 1859 deletions

View File

@ -110,7 +110,8 @@ describe('compiler (unbundled Angular)', () => {
});
}
function findLineAndColumn(file: string, token: string): {line: number, column: number} {
function findLineAndColumn(
file: string, token: string): {line: number | null, column: number | null} {
const index = file.indexOf(token);
if (index === -1) {
return {line: null, column: null};
@ -178,7 +179,7 @@ describe('compiler (unbundled Angular)', () => {
appDir['app.component.ts'] = createComponentSource(templateDecorator(template));
compileApp().then((genFile) => {
const sourceMap = extractSourceMap(genFile.source);
const sourceMap = extractSourceMap(genFile.source) !;
expect(sourceMap.file).toEqual(genFile.genFileUrl);
// the generated file contains code that is not mapped to
@ -199,7 +200,7 @@ describe('compiler (unbundled Angular)', () => {
appDir['app.component.ts'] = createComponentSource(templateDecorator(template));
compileApp().then((genFile) => {
const sourceMap = extractSourceMap(genFile.source);
const sourceMap = extractSourceMap(genFile.source) !;
expect(originalPositionFor(sourceMap, findLineAndColumn(genFile.source, `'span'`)))
.toEqual({line: 2, column: 3, source: ngUrl});
});
@ -211,7 +212,7 @@ describe('compiler (unbundled Angular)', () => {
appDir['app.component.ts'] = createComponentSource(templateDecorator(template));
compileApp().then((genFile) => {
const sourceMap = extractSourceMap(genFile.source);
const sourceMap = extractSourceMap(genFile.source) !;
expect(
originalPositionFor(sourceMap, findLineAndColumn(genFile.source, `someMethod()`)))
.toEqual({line: 2, column: 9, source: ngUrl});
@ -224,7 +225,7 @@ describe('compiler (unbundled Angular)', () => {
appDir['app.component.ts'] = createComponentSource(templateDecorator(template));
compileApp().then((genFile) => {
const sourceMap = extractSourceMap(genFile.source);
const sourceMap = extractSourceMap(genFile.source) !;
expect(
originalPositionFor(sourceMap, findLineAndColumn(genFile.source, `someMethod()`)))
.toEqual({line: 2, column: 9, source: ngUrl});
@ -235,7 +236,7 @@ describe('compiler (unbundled Angular)', () => {
appDir['app.component.ts'] = createComponentSource(templateDecorator('Hello World!'));
compileApp().then((genFile) => {
const sourceMap = extractSourceMap(genFile.source);
const sourceMap = extractSourceMap(genFile.source) !;
expect(originalPositionFor(sourceMap, {line: 1, column: 0}))
.toEqual({line: 1, column: 0, source: ngComponentPath});
});
@ -328,7 +329,7 @@ describe('compiler (unbundled Angular)', () => {
compile(host, aotHost, expectNoDiagnostics).then((generatedFiles) => {
const genFile = generatedFiles.find(genFile => genFile.srcFileUrl === '/app/app.ts');
const createComponentFactoryCall =
/ɵccf\([^)]*\)/m.exec(genFile.source)[0].replace(/\s*/g, '');
/ɵccf\([^)]*\)/m.exec(genFile.source) ![0].replace(/\s*/g, '');
// selector
expect(createComponentFactoryCall).toContain('my-comp');
// inputs

View File

@ -360,7 +360,7 @@ describe('StaticReflector', () => {
it('should record data about the error in the exception', () => {
let threw = false;
try {
const metadata = host.getMetadataFor('/tmp/src/invalid-metadata.ts');
const metadata = host.getMetadataFor('/tmp/src/invalid-metadata.ts') !;
expect(metadata).toBeDefined();
const moduleMetadata: any = metadata[0]['metadata'];
expect(moduleMetadata).toBeDefined();

View File

@ -382,7 +382,7 @@ export class MockSummaryResolver implements SummaryResolver<StaticSymbol> {
}
getImportAs(symbol: StaticSymbol): StaticSymbol {
const entry = this.importAs.find(entry => entry.symbol === symbol);
return entry ? entry.importAs : undefined;
return entry ? entry.importAs : undefined !;
}
isLibraryFile(filePath: string): boolean { return filePath.endsWith('.d.ts'); }
@ -429,7 +429,7 @@ export class MockStaticSymbolResolverHost implements StaticSymbolResolverHost {
}
if (modulePath.indexOf('.') === 0) {
const baseName = pathTo(containingFile, modulePath);
const baseName = pathTo(containingFile !, modulePath);
const tsName = baseName + '.ts';
if (this._getMetadataFor(tsName)) {
return tsName;

View File

@ -95,7 +95,7 @@ export function main() {
members: {aMethod: {__symbolic: 'function'}},
statics: {aStatic: true}
});
expect(summaries[1].type.type.reference)
expect(summaries[1].type !.type.reference)
.toBe(symbolCache.get('/tmp/some_service.d.ts', 'SomeService'));
});
@ -203,7 +203,7 @@ export function main() {
expect(summaries[2].metadata).toEqual('b');
// SomService is a transitive dep, but should have been serialized as well.
expect(summaries[3].symbol).toBe(symbolCache.get('/tmp/external_svc.d.ts', 'SomeService'));
expect(summaries[3].type.type.reference)
expect(summaries[3].type !.type.reference)
.toBe(symbolCache.get('/tmp/external_svc.d.ts', 'SomeService'));
});

View File

@ -18,7 +18,7 @@ export type MockDirectory = {
[name: string]: MockData | undefined;
};
export function isDirectory(data: MockData): data is MockDirectory {
export function isDirectory(data: MockData | undefined): data is MockDirectory {
return typeof data !== 'string';
}
@ -146,6 +146,7 @@ export class EmittingCompilerHost implements ts.CompilerHost {
if (content) {
return ts.createSourceFile(fileName, content, languageVersion, /* setParentNodes */ true);
}
throw new Error(`File not found '${fileName}'.`);
}
getDefaultLibFileName(options: ts.CompilerOptions): string { return 'lib.d.ts'; }
@ -235,7 +236,7 @@ export class MockCompilerHost implements ts.CompilerHost {
let result = open(fileName, this.data) != null;
if (!result && fileName.startsWith(MOCK_NODEMODULES_PREFIX)) {
const libraryPath = fileName.substr(MOCK_NODEMODULES_PREFIX.length - 1);
for (const library of this.libraries) {
for (const library of this.libraries !) {
if (library.has(libraryPath)) {
return true;
}
@ -252,7 +253,7 @@ export class MockCompilerHost implements ts.CompilerHost {
}
}
readFile(fileName: string): string { return this.getFileContent(fileName); }
readFile(fileName: string): string { return this.getFileContent(fileName) !; }
trace(s: string): void { this.traces.push(s); }
@ -265,10 +266,8 @@ export class MockCompilerHost implements ts.CompilerHost {
if (isDirectory(data)) {
return Object.keys(data).filter(k => isDirectory(data[k]));
}
return [];
} else {
return undefined;
}
return [];
}
// ts.CompilerHost
@ -283,7 +282,7 @@ export class MockCompilerHost implements ts.CompilerHost {
this.sourceFiles.set(fileName, result);
}
}
return result;
return result !;
}
getDefaultLibFileName(options: ts.CompilerOptions): string { return 'lib.d.ts'; }
@ -318,7 +317,7 @@ export class MockCompilerHost implements ts.CompilerHost {
const result = open(fileName, this.data);
if (!result && fileName.startsWith(MOCK_NODEMODULES_PREFIX)) {
const libraryPath = fileName.substr(MOCK_NODEMODULES_PREFIX.length - 1);
for (const library of this.libraries) {
for (const library of this.libraries !) {
if (library.has(libraryPath)) return library.get(libraryPath);
}
}
@ -367,9 +366,9 @@ export class MockAotCompilerHost implements AotCompilerHost {
tsFilesOnly() { this.dtsAreSource = false; }
// StaticSymbolResolverHost
getMetadataFor(modulePath: string): {[key: string]: any}[] {
getMetadataFor(modulePath: string): {[key: string]: any}[]|null {
if (!this.tsHost.fileExists(modulePath)) {
return undefined;
return null;
}
if (DTS.test(modulePath)) {
if (this.metadataVisible) {
@ -384,6 +383,7 @@ export class MockAotCompilerHost implements AotCompilerHost {
const metadata = this.metadataCollector.getMetadata(sf);
return metadata ? [metadata] : [];
}
return null;
}
moduleNameToFileName(moduleName: string, containingFile: string): string|null {
@ -439,11 +439,11 @@ export class MockMetadataBundlerHost implements MetadataBundlerHost {
}
}
function find(fileName: string, data: MockData): MockData|undefined {
function find(fileName: string, data: MockData | undefined): MockData|undefined {
if (!data) return undefined;
let names = fileName.split('/');
if (names.length && !names[0].length) names.shift();
let current = data;
let current: MockData|undefined = data;
for (let name of names) {
if (typeof current === 'string')
return undefined;
@ -454,7 +454,7 @@ function find(fileName: string, data: MockData): MockData|undefined {
return current;
}
function open(fileName: string, data: MockData): string|undefined {
function open(fileName: string, data: MockData | undefined): string|undefined {
let result = find(fileName, data);
if (typeof result === 'string') {
return result;
@ -462,7 +462,7 @@ function open(fileName: string, data: MockData): string|undefined {
return undefined;
}
function directoryExists(dirname: string, data: MockData): boolean {
function directoryExists(dirname: string, data: MockData | undefined): boolean {
let result = find(dirname, data);
return result && typeof result !== 'string';
return !!result && typeof result !== 'string';
}

View File

@ -274,7 +274,7 @@ export function main() {
it('should throw an error if a selector is being parsed while in the wrong mode', () => {
const cssCode = '.class > tag';
let capturedMessage: string;
let capturedMessage: string = undefined !;
try {
tokenize(cssCode, false, CssLexerMode.STYLE_BLOCK);
} catch (e) {
@ -282,7 +282,7 @@ export function main() {
}
expect(capturedMessage).toMatch(/Unexpected character \[\>\] at column 0:7 in expression/g);
capturedMessage = null;
capturedMessage = null !;
try {
tokenize(cssCode, false, CssLexerMode.SELECTOR);

View File

@ -111,26 +111,26 @@ export function main() {
expect(ast.rules.length).toEqual(1);
const rule = <CssKeyframeRuleAst>ast.rules[0];
expect(rule.name.strValue).toEqual('rotateMe');
expect(rule.name !.strValue).toEqual('rotateMe');
const block = <CssBlockAst>rule.block;
const fromRule = <CssKeyframeDefinitionAst>block.entries[0];
expect(fromRule.name.strValue).toEqual('from');
expect(fromRule.name !.strValue).toEqual('from');
const fromStyle = <CssDefinitionAst>(<CssBlockAst>fromRule.block).entries[0];
expect(fromStyle.property.strValue).toEqual('transform');
assertTokens(fromStyle.value.tokens, ['rotate', '(', '-360', 'deg', ')']);
const midRule = <CssKeyframeDefinitionAst>block.entries[1];
expect(midRule.name.strValue).toEqual('50%');
expect(midRule.name !.strValue).toEqual('50%');
const midStyle = <CssDefinitionAst>(<CssBlockAst>midRule.block).entries[0];
expect(midStyle.property.strValue).toEqual('transform');
assertTokens(midStyle.value.tokens, ['rotate', '(', '0', 'deg', ')']);
const toRule = <CssKeyframeDefinitionAst>block.entries[2];
expect(toRule.name.strValue).toEqual('to');
expect(toRule.name !.strValue).toEqual('to');
const toStyle = <CssDefinitionAst>(<CssBlockAst>toRule.block).entries[0];
expect(toStyle.property.strValue).toEqual('transform');
assertTokens(toStyle.value.tokens, ['rotate', '(', '360', 'deg', ')']);
@ -695,7 +695,7 @@ export function main() {
const ast = output.ast;
assertMatchesOffsetAndChar(ast.location.start, 0, '#');
assertMatchesOffsetAndChar(ast.location.end, 22, undefined);
assertMatchesOffsetAndChar(ast.location.end, 22, undefined !);
});
});

View File

@ -257,7 +257,7 @@ export function main() {
expect(captures.length).toEqual(1);
const keyframe1 = <CssKeyframeRuleAst>_getCaptureAst(captures, 0);
expect(keyframe1.name.strValue).toEqual('rotate');
expect(keyframe1.name !.strValue).toEqual('rotate');
expect(keyframe1.block.entries.length).toEqual(2);
});

View File

@ -5,6 +5,7 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CompileAnimationEntryMetadata} from '@angular/compiler';
import {CompileDirectiveMetadata, CompileStylesheetMetadata, CompileTemplateMetadata, CompileTypeMetadata} from '@angular/compiler/src/compile_metadata';
import {CompilerConfig} from '@angular/compiler/src/config';
import {DirectiveNormalizer} from '@angular/compiler/src/directive_normalizer';
@ -15,11 +16,137 @@ import {ViewEncapsulation} from '@angular/core/src/metadata/view';
import {TestBed} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal';
import {SyncAsyncResult, noUndefined} from '../src/util';
import {SpyResourceLoader} from './spies';
const SOME_MODULE_URL = 'package:some/module/a.js';
const SOME_HTTP_MODULE_URL = 'http://some/module/a.js';
function normalizeTemplate(normalizer: DirectiveNormalizer, o: {
ngModuleType?: any; componentType?: any; moduleUrl?: string; template?: string | null;
templateUrl?: string | null;
styles?: string[];
styleUrls?: string[];
interpolation?: [string, string] | null;
encapsulation?: ViewEncapsulation | null;
animations?: CompileAnimationEntryMetadata[];
}) {
return normalizer.normalizeTemplate({
ngModuleType: noUndefined(o.ngModuleType),
componentType: noUndefined(o.componentType),
moduleUrl: noUndefined(o.moduleUrl),
template: noUndefined(o.template),
templateUrl: noUndefined(o.templateUrl),
styles: noUndefined(o.styles),
styleUrls: noUndefined(o.styleUrls),
interpolation: noUndefined(o.interpolation),
encapsulation: noUndefined(o.encapsulation),
animations: noUndefined(o.animations)
});
}
function normalizeTemplateAsync(normalizer: DirectiveNormalizer, o: {
ngModuleType?: any; componentType?: any; moduleUrl?: string; template?: string | null;
templateUrl?: string | null;
styles?: string[];
styleUrls?: string[];
interpolation?: [string, string] | null;
encapsulation?: ViewEncapsulation | null;
animations?: CompileAnimationEntryMetadata[];
}) {
return normalizer.normalizeTemplateAsync({
ngModuleType: noUndefined(o.ngModuleType),
componentType: noUndefined(o.componentType),
moduleUrl: noUndefined(o.moduleUrl),
template: noUndefined(o.template),
templateUrl: noUndefined(o.templateUrl),
styles: noUndefined(o.styles),
styleUrls: noUndefined(o.styleUrls),
interpolation: noUndefined(o.interpolation),
encapsulation: noUndefined(o.encapsulation),
animations: noUndefined(o.animations)
});
}
function normalizeTemplateSync(normalizer: DirectiveNormalizer, o: {
ngModuleType?: any; componentType?: any; moduleUrl?: string; template?: string | null;
templateUrl?: string | null;
styles?: string[];
styleUrls?: string[];
interpolation?: [string, string] | null;
encapsulation?: ViewEncapsulation | null;
animations?: CompileAnimationEntryMetadata[];
}): CompileTemplateMetadata {
return normalizer.normalizeTemplateSync({
ngModuleType: noUndefined(o.ngModuleType),
componentType: noUndefined(o.componentType),
moduleUrl: noUndefined(o.moduleUrl),
template: noUndefined(o.template),
templateUrl: noUndefined(o.templateUrl),
styles: noUndefined(o.styles),
styleUrls: noUndefined(o.styleUrls),
interpolation: noUndefined(o.interpolation),
encapsulation: noUndefined(o.encapsulation),
animations: noUndefined(o.animations)
});
}
function compileTemplateMetadata({encapsulation, template, templateUrl, styles, styleUrls,
externalStylesheets, animations, ngContentSelectors,
interpolation, isInline}: {
encapsulation?: ViewEncapsulation | null,
template?: string | null,
templateUrl?: string | null,
styles?: string[],
styleUrls?: string[],
externalStylesheets?: CompileStylesheetMetadata[],
ngContentSelectors?: string[],
animations?: any[],
interpolation?: [string, string] | null,
isInline?: boolean
}): CompileTemplateMetadata {
return new CompileTemplateMetadata({
encapsulation: encapsulation || null,
template: template || null,
templateUrl: templateUrl || null,
styles: styles || [],
styleUrls: styleUrls || [],
externalStylesheets: externalStylesheets || [],
ngContentSelectors: ngContentSelectors || [],
animations: animations || [],
interpolation: interpolation || null,
isInline: !!isInline,
});
}
function normalizeLoadedTemplate(
normalizer: DirectiveNormalizer, o: {
ngModuleType?: any; componentType?: any; moduleUrl?: string; template?: string | null;
templateUrl?: string | null;
styles?: string[];
styleUrls?: string[];
interpolation?: [string, string] | null;
encapsulation?: ViewEncapsulation | null;
animations?: CompileAnimationEntryMetadata[];
},
template: string, templateAbsUrl: string) {
return normalizer.normalizeLoadedTemplate(
{
ngModuleType: o.ngModuleType || null,
componentType: o.componentType || null,
moduleUrl: o.moduleUrl || '',
template: o.template || null,
templateUrl: o.templateUrl || null,
styles: o.styles || [],
styleUrls: o.styleUrls || [],
interpolation: o.interpolation || null,
encapsulation: o.encapsulation || null,
animations: o.animations || null,
},
template, templateAbsUrl);
}
export function main() {
describe('DirectiveNormalizer', () => {
beforeEach(() => { TestBed.configureCompiler({providers: TEST_COMPILER_PROVIDERS}); });
@ -27,46 +154,50 @@ export function main() {
describe('normalizeDirective', () => {
it('should throw if no template was specified',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
expect(() => normalizer.normalizeTemplate({
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
})).toThrowError('No template specified for component SomeComp');
expect(() => normalizeTemplate(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
}))
.toThrowError('No template specified for component SomeComp');
}));
it('should throw if template is not a string',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
expect(() => normalizer.normalizeTemplate({
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
template: <any>{}
})).toThrowError('The template specified for component SomeComp is not a string');
expect(() => normalizeTemplate(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
template: <any>{}
}))
.toThrowError('The template specified for component SomeComp is not a string');
}));
it('should throw if templateUrl is not a string',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
expect(() => normalizer.normalizeTemplate({
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
templateUrl: <any>{}
})).toThrowError('The templateUrl specified for component SomeComp is not a string');
expect(() => normalizeTemplate(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
templateUrl: <any>{}
}))
.toThrowError('The templateUrl specified for component SomeComp is not a string');
}));
it('should throw if both template and templateUrl are defined',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
expect(() => normalizer.normalizeTemplate({
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
template: '',
templateUrl: '',
})).toThrowError(`'SomeComp' component cannot define both template and templateUrl`);
expect(() => normalizeTemplate(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
template: '',
templateUrl: '',
}))
.toThrowError(`'SomeComp' component cannot define both template and templateUrl`);
}));
});
describe('normalizeTemplateSync', () => {
it('should store the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeTemplateSync({
const template = normalizeTemplateSync(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -83,7 +214,7 @@ export function main() {
it('should resolve styles on the annotation against the moduleUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeTemplateSync({
const template = normalizeTemplateSync(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -98,7 +229,7 @@ export function main() {
it('should resolve styles in the template against the moduleUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeTemplateSync({
const template = normalizeTemplateSync(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -113,7 +244,7 @@ export function main() {
it('should use ViewEncapsulation.Emulated by default',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeTemplateSync({
const template = normalizeTemplateSync(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -131,13 +262,13 @@ export function main() {
[CompilerConfig, DirectiveNormalizer],
(config: CompilerConfig, normalizer: DirectiveNormalizer) => {
config.defaultEncapsulation = ViewEncapsulation.None;
const template = normalizer.normalizeTemplateSync({
const template = normalizeTemplateSync(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
encapsulation: null,
encapsulation: undefined,
template: '',
templateUrl: null,
templateUrl: undefined,
styles: [],
styleUrls: ['test.css']
});
@ -153,23 +284,21 @@ export function main() {
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect('package:some/module/sometplurl.html', 'a');
normalizer
.normalizeTemplateAsync({
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
encapsulation: null,
template: null,
templateUrl: 'sometplurl.html',
styles: [],
styleUrls: ['test.css']
})
.then((template: CompileTemplateMetadata) => {
expect(template.template).toEqual('a');
expect(template.templateUrl).toEqual('package:some/module/sometplurl.html');
expect(template.isInline).toBe(false);
async.done();
});
normalizeTemplateAsync(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
encapsulation: null,
template: null,
templateUrl: 'sometplurl.html',
styles: [],
styleUrls: ['test.css']
}).then((template: CompileTemplateMetadata) => {
expect(template.template).toEqual('a');
expect(template.templateUrl).toEqual('package:some/module/sometplurl.html');
expect(template.isInline).toBe(false);
async.done();
});
resourceLoader.flush();
}));
@ -179,21 +308,19 @@ export function main() {
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect('package:some/module/tpl/sometplurl.html', '');
normalizer
.normalizeTemplateAsync({
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
encapsulation: null,
template: null,
templateUrl: 'tpl/sometplurl.html',
styles: [],
styleUrls: ['test.css']
})
.then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
async.done();
});
normalizeTemplateAsync(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
encapsulation: null,
template: null,
templateUrl: 'tpl/sometplurl.html',
styles: [],
styleUrls: ['test.css']
}).then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
async.done();
});
resourceLoader.flush();
}));
@ -204,21 +331,19 @@ export function main() {
resourceLoader: MockResourceLoader) => {
resourceLoader.expect(
'package:some/module/tpl/sometplurl.html', '<style>@import test.css</style>');
normalizer
.normalizeTemplateAsync({
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
encapsulation: null,
template: null,
templateUrl: 'tpl/sometplurl.html',
styles: [],
styleUrls: []
})
.then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/tpl/test.css']);
async.done();
});
normalizeTemplateAsync(normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
encapsulation: null,
template: null,
templateUrl: 'tpl/sometplurl.html',
styles: [],
styleUrls: []
}).then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/tpl/test.css']);
async.done();
});
resourceLoader.flush();
}));
@ -238,7 +363,7 @@ export function main() {
resourceLoader: SpyResourceLoader) => {
programResourceLoaderSpy(resourceLoader, {'package:some/module/test.css': 'a'});
normalizer
.normalizeExternalStylesheets(new CompileTemplateMetadata({
.normalizeExternalStylesheets(compileTemplateMetadata({
template: '',
templateUrl: '',
styleUrls: ['package:some/module/test.css']
@ -264,7 +389,7 @@ export function main() {
'package:some/module/test2.css': 'b'
});
normalizer
.normalizeExternalStylesheets(new CompileTemplateMetadata({
.normalizeExternalStylesheets(compileTemplateMetadata({
template: '',
templateUrl: '',
styleUrls: ['package:some/module/test.css']
@ -301,8 +426,8 @@ export function main() {
};
Promise
.all([
normalizer.normalizeTemplateAsync(prenormMeta),
normalizer.normalizeTemplateAsync(prenormMeta)
normalizeTemplateAsync(normalizer, prenormMeta),
normalizeTemplateAsync(normalizer, prenormMeta)
])
.then((templates: CompileTemplateMetadata[]) => {
expect(templates[0].template).toEqual('a');
@ -319,8 +444,8 @@ export function main() {
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const viewEncapsulation = ViewEncapsulation.Native;
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -334,8 +459,8 @@ export function main() {
it('should keep the template as html',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -349,8 +474,8 @@ export function main() {
it('should collect ngContent',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -364,8 +489,8 @@ export function main() {
it('should normalize ngContent wildcard selector',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -380,8 +505,8 @@ export function main() {
it('should collect top level styles in the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -395,8 +520,8 @@ export function main() {
it('should collect styles inside in elements',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -410,8 +535,8 @@ export function main() {
it('should collect styleUrls in the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -425,8 +550,8 @@ export function main() {
it('should collect styleUrls in elements',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -440,8 +565,8 @@ export function main() {
it('should ignore link elements with non stylesheet rel attribute',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -455,8 +580,8 @@ export function main() {
it('should ignore link elements with absolute urls but non package: scheme',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -470,8 +595,8 @@ export function main() {
it('should extract @import style urls into styleAbsUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -486,8 +611,8 @@ export function main() {
it('should not resolve relative urls in inline styles',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -501,8 +626,8 @@ export function main() {
it('should resolve relative style urls in styleUrls',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -517,8 +642,8 @@ export function main() {
it('should resolve relative style urls in styleUrls with http directive url',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_HTTP_MODULE_URL,
@ -533,8 +658,8 @@ export function main() {
it('should normalize ViewEncapsulation.Emulated to ViewEncapsulation.None if there are no styles nor stylesheets',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -548,8 +673,8 @@ export function main() {
it('should ignore ng-content in elements with ngNonBindable',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,
@ -564,8 +689,8 @@ export function main() {
it('should still collect <style> in elements with ngNonBindable',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
const template = normalizer.normalizeLoadedTemplate(
{
const template = normalizeLoadedTemplate(
normalizer, {
ngModuleType: null,
componentType: SomeComp,
moduleUrl: SOME_MODULE_URL,

View File

@ -28,18 +28,18 @@ export function main() {
function parseTemplateBindingsResult(
text: string, location: any = null, prefix?: string): TemplateBindingParseResult {
return createParser().parseTemplateBindings(prefix, text, location);
return createParser().parseTemplateBindings(prefix || null, text, location);
}
function parseTemplateBindings(
text: string, location: any = null, prefix?: string): TemplateBinding[] {
return parseTemplateBindingsResult(text, location, prefix).templateBindings;
}
function parseInterpolation(text: string, location: any = null): ASTWithSource {
function parseInterpolation(text: string, location: any = null): ASTWithSource|null {
return createParser().parseInterpolation(text, location);
}
function splitInterpolation(text: string, location: any = null): SplitInterpolation {
function splitInterpolation(text: string, location: any = null): SplitInterpolation|null {
return createParser().splitInterpolation(text, location);
}
@ -48,7 +48,7 @@ export function main() {
}
function checkInterpolation(exp: string, expected?: string) {
const ast = parseInterpolation(exp);
const ast = parseInterpolation(exp) !;
if (expected == null) expected = exp;
expect(unparse(ast)).toEqual(expected);
validate(ast);
@ -475,7 +475,7 @@ export function main() {
() => { expect(parseInterpolation('nothing')).toBe(null); });
it('should parse no prefix/suffix interpolation', () => {
const ast = parseInterpolation('{{a}}').ast as Interpolation;
const ast = parseInterpolation('{{a}}') !.ast as Interpolation;
expect(ast.strings).toEqual(['', '']);
expect(ast.expressions.length).toEqual(1);
expect(ast.expressions[0].name).toEqual('a');
@ -483,18 +483,18 @@ export function main() {
it('should parse prefix/suffix with multiple interpolation', () => {
const originalExp = 'before {{ a }} middle {{ b }} after';
const ast = parseInterpolation(originalExp).ast;
const ast = parseInterpolation(originalExp) !.ast;
expect(unparse(ast)).toEqual(originalExp);
validate(ast);
});
it('should report empty interpolation expressions', () => {
expectError(
parseInterpolation('{{}}'),
parseInterpolation('{{}}') !,
'Blank expressions are not allowed in interpolated strings');
expectError(
parseInterpolation('foo {{ }}'),
parseInterpolation('foo {{ }}') !,
'Parser Error: Blank expressions are not allowed in interpolated strings');
});
@ -507,7 +507,8 @@ export function main() {
it('should support custom interpolation', () => {
const parser = new Parser(new Lexer());
const ast = parser.parseInterpolation('{% a %}', null, {start: '{%', end: '%}'}).ast as any;
const ast =
parser.parseInterpolation('{% a %}', null, {start: '{%', end: '%}'}) !.ast as any;
expect(ast.strings).toEqual(['', '']);
expect(ast.expressions.length).toEqual(1);
expect(ast.expressions[0].name).toEqual('a');
@ -586,12 +587,12 @@ export function main() {
describe('offsets', () => {
it('should retain the offsets of an interpolation', () => {
const interpolations = splitInterpolation('{{a}} {{b}} {{c}}');
const interpolations = splitInterpolation('{{a}} {{b}} {{c}}') !;
expect(interpolations.offsets).toEqual([2, 9, 16]);
});
it('should retain the offsets into the expression AST of interpolations', () => {
const source = parseInterpolation('{{a}} {{b}} {{c}}');
const source = parseInterpolation('{{a}} {{b}} {{c}}') !;
const interpolation = source.ast as Interpolation;
expect(interpolation.expressions.map(e => e.span.start)).toEqual([2, 9, 16]);
});

View File

@ -67,7 +67,7 @@ class Unparser implements AstVisitor {
}
visitFunctionCall(ast: FunctionCall, context: any) {
this._visit(ast.target);
this._visit(ast.target !);
this._expression += '(';
let isFirst = true;
ast.args.forEach(arg => {

View File

@ -285,7 +285,7 @@ export function main() {
});
it('should allow nested implicit elements', () => {
let result: any[];
let result: any[] = undefined !;
expect(() => {
result = extract('<div>outer<div>inner</div></div>', ['div']);
@ -490,7 +490,7 @@ function fakeTranslate(
messages.forEach(message => {
const id = digest(message);
const text = serializeI18nNodes(message.nodes).join('').replace(/</g, '[');
i18nMsgMap[id] = [new i18n.Text(`**${text}**`, null)];
i18nMsgMap[id] = [new i18n.Text(`**${text}**`, null !)];
});
const translations = new TranslationBundle(i18nMsgMap, null, digest);

View File

@ -36,13 +36,13 @@ export function main(): void {
const visitor = new RecurseVisitor();
const container = new i18n.Container(
[
new i18n.Text('', null),
new i18n.Placeholder('', '', null),
new i18n.IcuPlaceholder(null, '', null),
new i18n.Text('', null !),
new i18n.Placeholder('', '', null !),
new i18n.IcuPlaceholder(null !, '', null !),
],
null);
const tag = new i18n.TagPlaceholder('', {}, '', '', [container], false, null);
const icu = new i18n.Icu('', '', {tag}, null);
null !);
const tag = new i18n.TagPlaceholder('', {}, '', '', [container], false, null !);
const icu = new i18n.Icu('', '', {tag}, null !);
icu.visit(visitor);
expect(visitor.textCount).toEqual(1);

View File

@ -117,7 +117,7 @@ export function main(): void {
</translationbundle>`;
// Invalid messages should not cause the parser to throw
let i18nNodesByMsgId: {[id: string]: i18n.Node[]};
let i18nNodesByMsgId: {[id: string]: i18n.Node[]} = undefined !;
expect(() => {
i18nNodesByMsgId = serializer.load(XTB, 'url').i18nNodesByMsgId;
}).not.toThrow();

View File

@ -18,11 +18,11 @@ export function main(): void {
describe('TranslationBundle', () => {
const file = new ParseSourceFile('content', 'url');
const location = new ParseLocation(file, 0, 0, 0);
const span = new ParseSourceSpan(location, null);
const span = new ParseSourceSpan(location, null !);
const srcNode = new i18n.Text('src', span);
it('should translate a plain message', () => {
const msgMap = {foo: [new i18n.Text('bar', null)]};
const msgMap = {foo: [new i18n.Text('bar', null !)]};
const tb = new TranslationBundle(msgMap, null, (_) => 'foo');
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(serializeNodes(tb.get(msg))).toEqual(['bar']);
@ -31,8 +31,8 @@ export function main(): void {
it('should translate a message with placeholder', () => {
const msgMap = {
foo: [
new i18n.Text('bar', null),
new i18n.Placeholder('', 'ph1', null),
new i18n.Text('bar', null !),
new i18n.Placeholder('', 'ph1', null !),
]
};
const phMap = {
@ -46,12 +46,12 @@ export function main(): void {
it('should translate a message with placeholder referencing messages', () => {
const msgMap = {
foo: [
new i18n.Text('--', null),
new i18n.Placeholder('', 'ph1', null),
new i18n.Text('++', null),
new i18n.Text('--', null !),
new i18n.Placeholder('', 'ph1', null !),
new i18n.Text('++', null !),
],
ref: [
new i18n.Text('*refMsg*', null),
new i18n.Text('*refMsg*', null !),
],
};
const refMsg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
@ -70,13 +70,13 @@ export function main(): void {
const digest = (_: any) => `no matching id`;
// Empty message map -> use source messages in Ignore mode
let tb = new TranslationBundle({}, null, digest, null, MissingTranslationStrategy.Ignore);
let tb = new TranslationBundle({}, null, digest, null !, MissingTranslationStrategy.Ignore);
expect(serializeNodes(tb.get(messages[0])).join('')).toEqual(src);
// Empty message map -> use source messages in Warning mode
tb = new TranslationBundle({}, null, digest, null, MissingTranslationStrategy.Warning);
tb = new TranslationBundle({}, null, digest, null !, MissingTranslationStrategy.Warning);
expect(serializeNodes(tb.get(messages[0])).join('')).toEqual(src);
// Empty message map -> throw in Error mode
tb = new TranslationBundle({}, null, digest, null, MissingTranslationStrategy.Error);
tb = new TranslationBundle({}, null, digest, null !, MissingTranslationStrategy.Error);
expect(() => serializeNodes(tb.get(messages[0])).join('')).toThrow();
});
@ -84,7 +84,7 @@ export function main(): void {
it('should report unknown placeholders', () => {
const msgMap = {
foo: [
new i18n.Text('bar', null),
new i18n.Text('bar', null !),
new i18n.Placeholder('', 'ph1', span),
]
};
@ -95,7 +95,7 @@ export function main(): void {
it('should report missing translation', () => {
const tb =
new TranslationBundle({}, null, (_) => 'foo', null, MissingTranslationStrategy.Error);
new TranslationBundle({}, null, (_) => 'foo', null !, MissingTranslationStrategy.Error);
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(() => tb.get(msg)).toThrowError(/Missing translation for message "foo"/);
});
@ -108,7 +108,7 @@ export function main(): void {
};
const tb = new TranslationBundle(
{}, 'en', (_) => 'foo', null, MissingTranslationStrategy.Warning, console);
{}, 'en', (_) => 'foo', null !, MissingTranslationStrategy.Warning, console);
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(() => tb.get(msg)).not.toThrowError();
@ -117,8 +117,8 @@ export function main(): void {
});
it('should not report missing translation with MissingTranslationStrategy.Ignore', () => {
const tb =
new TranslationBundle({}, null, (_) => 'foo', null, MissingTranslationStrategy.Ignore);
const tb = new TranslationBundle(
{}, null, (_) => 'foo', null !, MissingTranslationStrategy.Ignore);
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(() => tb.get(msg)).not.toThrowError();
});
@ -132,15 +132,15 @@ export function main(): void {
let count = 0;
const digest = (_: any) => count++ ? 'ref' : 'foo';
const tb =
new TranslationBundle(msgMap, null, digest, null, MissingTranslationStrategy.Error);
new TranslationBundle(msgMap, null, digest, null !, MissingTranslationStrategy.Error);
expect(() => tb.get(msg)).toThrowError(/Missing translation for message "ref"/);
});
it('should report invalid translated html', () => {
const msgMap = {
foo: [
new i18n.Text('text', null),
new i18n.Placeholder('', 'ph1', null),
new i18n.Text('text', null !),
new i18n.Placeholder('', 'ph1', null !),
]
};
const phMap = {

View File

@ -16,7 +16,7 @@ export function main() {
let fixture: ComponentFixture<TestComponent>;
describe('directives', () => {
describe('directiv es', () => {
it('should support dotted selectors', async(() => {
@Directive({selector: '[dot.name]'})
class MyDir {

View File

@ -26,9 +26,9 @@ class SomeMetadata implements SomeMetadataType {
arrayProp: any[];
constructor(options: SomeMetadataType) {
this.plainProp = options.plainProp;
this._getterProp = options.getterProp;
this.arrayProp = options.arrayProp;
this.plainProp = options.plainProp !;
this._getterProp = options.getterProp !;
this.arrayProp = options.arrayProp !;
}
}
@ -42,7 +42,7 @@ class OtherMetadata extends SomeMetadata implements OtherMetadataType {
arrayProp: options.arrayProp
});
this.otherPlainProp = options.otherPlainProp;
this.otherPlainProp = options.otherPlainProp !;
}
}

View File

@ -215,7 +215,7 @@ export function main() {
it('should throw with descriptive error message when null is passed to declarations',
inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => {
@NgModule({declarations: [null]})
@NgModule({declarations: [null !]})
class ModuleWithNullDeclared {
}
expect(() => resolver.loadNgModuleDirectiveAndPipeMetadata(ModuleWithNullDeclared, true))
@ -225,7 +225,7 @@ export function main() {
it('should throw with descriptive error message when null is passed to imports',
inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => {
@NgModule({imports: [null]})
@NgModule({imports: [null !]})
class ModuleWithNullImported {
}
expect(() => resolver.loadNgModuleDirectiveAndPipeMetadata(ModuleWithNullImported, true))
@ -246,7 +246,7 @@ export function main() {
it('should throw with descriptive error message when encounter invalid provider',
inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => {
@NgModule({providers: [{provide: SimpleService, useClass: undefined}]})
@NgModule({providers: [{provide: SimpleService, useClass: undefined !}]})
class SomeModule {
}
@ -256,7 +256,7 @@ export function main() {
it('should throw with descriptive error message when provider is undefined',
inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => {
@NgModule({providers: [undefined]})
@NgModule({providers: [undefined !]})
class SomeModule {
}
@ -288,10 +288,10 @@ export function main() {
it('should throw with descriptive error message when null or undefined is passed to module bootstrap',
inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => {
@NgModule({bootstrap: [null]})
@NgModule({bootstrap: [null !]})
class ModuleWithNullBootstrap {
}
@NgModule({bootstrap: [undefined]})
@NgModule({bootstrap: [undefined !]})
class ModuleWithUndefinedBootstrap {
}
@ -410,7 +410,7 @@ export function main() {
class MyModule {
}
const modMeta = resolver.getNgModuleMetadata(MyModule);
const modMeta = resolver.getNgModuleMetadata(MyModule) !;
expect(modMeta.declaredDirectives.length).toBe(1);
expect(modMeta.declaredDirectives[0].reference).toBe(MyComp);
}));
@ -480,11 +480,12 @@ class MyBrokenComp2 {
class SimpleService {
}
@Component({selector: 'my-broken-comp', template: '', providers: [SimpleService, null, [null]]})
@Component({selector: 'my-broken-comp', template: '', providers: [SimpleService, null !, [null]]})
class MyBrokenComp3 {
}
@Component({selector: 'my-broken-comp', template: '', viewProviders: [null, SimpleService, [null]]})
@Component(
{selector: 'my-broken-comp', template: '', viewProviders: [null !, SimpleService, [null]]})
class MyBrokenComp4 {
}

View File

@ -78,7 +78,7 @@ class _Humanizer implements html.Visitor {
private _appendContext(ast: html.Node, input: any[]): any[] {
if (!this.includeSourceSpan) return input;
input.push(ast.sourceSpan.toString());
input.push(ast.sourceSpan !.toString());
return input;
}
}

View File

@ -395,11 +395,11 @@ export function main() {
it('should set the start and end source spans', () => {
const node = <html.Element>parser.parse('<div>a</div>', 'TestComp').rootNodes[0];
expect(node.startSourceSpan.start.offset).toEqual(0);
expect(node.startSourceSpan.end.offset).toEqual(5);
expect(node.startSourceSpan !.start.offset).toEqual(0);
expect(node.startSourceSpan !.end.offset).toEqual(5);
expect(node.endSourceSpan.start.offset).toEqual(6);
expect(node.endSourceSpan.end.offset).toEqual(12);
expect(node.endSourceSpan !.start.offset).toEqual(6);
expect(node.endSourceSpan !.end.offset).toEqual(12);
});
it('should support expansion form', () => {
@ -420,8 +420,8 @@ export function main() {
it('should report a value span for an attibute with a value', () => {
const ast = parser.parse('<div bar="12"></div>', 'TestComp');
const attr = (ast.rootNodes[0] as html.Element).attrs[0];
expect(attr.valueSpan.start.offset).toEqual(9);
expect(attr.valueSpan.end.offset).toEqual(13);
expect(attr.valueSpan !.start.offset).toEqual(9);
expect(attr.valueSpan !.end.offset).toEqual(13);
});
});

View File

@ -56,28 +56,28 @@ export function main() {
const nodes = expand(`{messages.length, plural,=0 {<b>bold</b>}}`).nodes;
const container: html.Element = <html.Element>nodes[0];
expect(container.sourceSpan.start.col).toEqual(0);
expect(container.sourceSpan.end.col).toEqual(42);
expect(container.startSourceSpan.start.col).toEqual(0);
expect(container.startSourceSpan.end.col).toEqual(42);
expect(container.endSourceSpan.start.col).toEqual(0);
expect(container.endSourceSpan.end.col).toEqual(42);
expect(container.sourceSpan !.start.col).toEqual(0);
expect(container.sourceSpan !.end.col).toEqual(42);
expect(container.startSourceSpan !.start.col).toEqual(0);
expect(container.startSourceSpan !.end.col).toEqual(42);
expect(container.endSourceSpan !.start.col).toEqual(0);
expect(container.endSourceSpan !.end.col).toEqual(42);
const switchExp = container.attrs[0];
expect(switchExp.sourceSpan.start.col).toEqual(1);
expect(switchExp.sourceSpan.end.col).toEqual(16);
const template: html.Element = <html.Element>container.children[0];
expect(template.sourceSpan.start.col).toEqual(25);
expect(template.sourceSpan.end.col).toEqual(41);
expect(template.sourceSpan !.start.col).toEqual(25);
expect(template.sourceSpan !.end.col).toEqual(41);
const switchCheck = template.attrs[0];
expect(switchCheck.sourceSpan.start.col).toEqual(25);
expect(switchCheck.sourceSpan.end.col).toEqual(28);
const b: html.Element = <html.Element>template.children[0];
expect(b.sourceSpan.start.col).toEqual(29);
expect(b.endSourceSpan.end.col).toEqual(40);
expect(b.sourceSpan !.start.col).toEqual(29);
expect(b.endSourceSpan !.end.col).toEqual(40);
});
it('should handle other special forms', () => {

View File

@ -443,7 +443,7 @@ export function main() {
});
it('should parse interpolation with custom markers', () => {
expect(tokenizeAndHumanizeParts('{% a %}', null, {start: '{%', end: '%}'})).toEqual([
expect(tokenizeAndHumanizeParts('{% a %}', null !, {start: '{%', end: '%}'})).toEqual([
[lex.TokenType.TEXT, '{% a %}'],
[lex.TokenType.EOF],
]);
@ -769,7 +769,7 @@ export function main() {
const file = new ParseSourceFile(src, 'file://');
const location = new ParseLocation(file, 12, 123, 456);
const span = new ParseSourceSpan(location, location);
const error = new lex.TokenError('**ERROR**', null, span);
const error = new lex.TokenError('**ERROR**', null !, span);
expect(error.toString())
.toEqual(`**ERROR** ("\n222\n333\n[ERROR ->]E\n444\n555\n"): file://@123:456`);
});

View File

@ -25,7 +25,7 @@ export function main() {
ctx.print(createSourceSpan(fileA, 1), 'o1');
ctx.print(createSourceSpan(fileB, 0), 'o2');
ctx.print(createSourceSpan(fileB, 1), 'o3');
const sm = ctx.toSourceMapGenerator('o.ts', 'o.js').toJSON();
const sm = ctx.toSourceMapGenerator('o.ts', 'o.js').toJSON() !;
expect(sm.sources).toEqual([fileA.url, fileB.url]);
expect(sm.sourcesContent).toEqual([fileA.content, fileB.content]);
});
@ -43,7 +43,7 @@ export function main() {
it('should be able to shift the content', () => {
ctx.print(createSourceSpan(fileA, 0), 'fileA-0');
const sm = ctx.toSourceMapGenerator('o.ts', 'o.js', 10).toJSON();
const sm = ctx.toSourceMapGenerator('o.ts', 'o.js', 10).toJSON() !;
expect(originalPositionFor(sm, {line: 11, column: 0})).toEqual({
line: 1,
column: 0,
@ -111,9 +111,9 @@ export function main() {
// All lines / columns indexes are 0-based
// Note: source-map line indexes are 1-based, column 0-based
function expectMap(
ctx: EmitterVisitorContext, genLine: number, genCol: number, source: string = null,
srcLine: number = null, srcCol: number = null) {
const sm = ctx.toSourceMapGenerator('o.ts', 'o.js').toJSON();
ctx: EmitterVisitorContext, genLine: number, genCol: number, source: string | null = null,
srcLine: number | null = null, srcCol: number | null = null) {
const sm = ctx.toSourceMapGenerator('o.ts', 'o.js').toJSON() !;
const genPosition = {line: genLine + 1, column: genCol};
const origPosition = originalPositionFor(sm, genPosition);
expect(origPosition.source).toEqual(source);
@ -123,7 +123,7 @@ function expectMap(
// returns the number of segments per line
function nbSegmentsPerLine(ctx: EmitterVisitorContext) {
const sm = ctx.toSourceMapGenerator('o.ts', 'o.js').toJSON();
const sm = ctx.toSourceMapGenerator('o.ts', 'o.js').toJSON() !;
const lines = sm.mappings.split(';');
return lines.map(l => {
const m = l.match(/,/g);

View File

@ -23,8 +23,8 @@ class SimpleJsImportGenerator implements ImportResolver {
fileNameToModuleName(importedUrlStr: string, moduleUrlStr: string): string {
return importedUrlStr;
}
getImportAs(symbol: StaticSymbol): StaticSymbol { return null; }
getTypeArity(symbol: StaticSymbol): number /*|null*/ { return null; }
getImportAs(symbol: StaticSymbol): StaticSymbol|null { return null; }
getTypeArity(symbol: StaticSymbol): number|null { return null; }
}
export function main() {
@ -39,12 +39,12 @@ export function main() {
});
function emitSourceMap(
stmt: o.Statement | o.Statement[], exportedVars: string[] = null,
stmt: o.Statement | o.Statement[], exportedVars: string[] | null = null,
preamble?: string): SourceMap {
const stmts = Array.isArray(stmt) ? stmt : [stmt];
const source = emitter.emitStatements(
someSourceFilePath, someGenFilePath, stmts, exportedVars || [], preamble);
return extractSourceMap(source);
return extractSourceMap(source) !;
}
describe('source maps', () => {

View File

@ -29,8 +29,8 @@ class SimpleJsImportGenerator implements ImportResolver {
fileNameToModuleName(importedUrlStr: string, moduleUrlStr: string): string {
return importedUrlStr;
}
getImportAs(symbol: StaticSymbol): StaticSymbol { return null; }
getTypeArity(symbol: StaticSymbol): number /*|null*/ { return null; }
getImportAs(symbol: StaticSymbol): StaticSymbol|null { return null; }
getTypeArity(symbol: StaticSymbol): number|null { return null; }
}
export function main() {
@ -49,7 +49,8 @@ export function main() {
someVar = o.variable('someVar');
});
function emitStmt(stmt: o.Statement, exportedVars: string[] = null, preamble?: string): string {
function emitStmt(
stmt: o.Statement, exportedVars: string[] | null = null, preamble?: string): string {
const source = emitter.emitStatements(
someSourceFilePath, someGenFilePath, [stmt], exportedVars || [], preamble);
return stripSourceMapAndNewLine(source);
@ -224,15 +225,15 @@ export function main() {
beforeEach(() => { callSomeMethod = o.THIS_EXPR.callMethod('someMethod', []).toStmt(); });
it('should support declaring classes', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [
]))).toEqual(['function SomeClass() {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, []), ['SomeClass']))
expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, []), ['SomeClass']))
.toEqual([
'function SomeClass() {', '}',
`Object.defineProperty(exports, 'SomeClass', { get: function() { return SomeClass; }});`
].join('\n'));
expect(
emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null, [])))
expect(emitStmt(
new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null !, [])))
.toEqual([
'function SomeClass() {', '}',
'SomeClass.prototype = Object.create(SomeSuperClass.prototype);'
@ -241,23 +242,24 @@ export function main() {
it('should support declaring constructors', () => {
const superCall = o.SUPER_EXPR.callFn([o.variable('someParam')]).toStmt();
expect(emitStmt(
new o.ClassStmt('SomeClass', null, [], [], new o.ClassMethod(null, [], []), [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null !, [], [], new o.ClassMethod(null !, [], []), [])))
.toEqual(['function SomeClass() {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [],
new o.ClassMethod(null, [new o.FnParam('someParam')], []), [])))
'SomeClass', null !, [], [],
new o.ClassMethod(null !, [new o.FnParam('someParam')], []), [])))
.toEqual(['function SomeClass(someParam) {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', o.variable('SomeSuperClass'), [], [],
new o.ClassMethod(null, [], [superCall]), [])))
new o.ClassMethod(null !, [], [superCall]), [])))
.toEqual([
'function SomeClass() {', ' var self = this;',
' SomeSuperClass.call(this, someParam);', '}',
'SomeClass.prototype = Object.create(SomeSuperClass.prototype);'
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], new o.ClassMethod(null, [], [callSomeMethod]), [])))
expect(
emitStmt(new o.ClassStmt(
'SomeClass', null !, [], [], new o.ClassMethod(null !, [], [callSomeMethod]), [])))
.toEqual([
'function SomeClass() {', ' var self = this;', ' self.someMethod();', '}'
].join('\n'));
@ -265,14 +267,14 @@ export function main() {
it('should support declaring getters', () => {
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [])], null, [])))
'SomeClass', null !, [], [new o.ClassGetter('someGetter', [])], null !, [])))
.toEqual([
'function SomeClass() {', '}',
`Object.defineProperty(SomeClass.prototype, 'someGetter', { get: function() {`, `}});`
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [callSomeMethod])], null,
[])))
'SomeClass', null !, [], [new o.ClassGetter('someGetter', [callSomeMethod])],
null !, [])))
.toEqual([
'function SomeClass() {', '}',
`Object.defineProperty(SomeClass.prototype, 'someGetter', { get: function() {`,
@ -282,19 +284,19 @@ export function main() {
it('should support methods', () => {
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null, [new o.ClassMethod('someMethod', [], [])])))
'SomeClass', null !, [], [], null !, [new o.ClassMethod('someMethod', [], [])])))
.toEqual([
'function SomeClass() {', '}', 'SomeClass.prototype.someMethod = function() {', '};'
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
'SomeClass', null !, [], [], null !,
[new o.ClassMethod('someMethod', [new o.FnParam('someParam')], [])])))
.toEqual([
'function SomeClass() {', '}',
'SomeClass.prototype.someMethod = function(someParam) {', '};'
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
'SomeClass', null !, [], [], null !,
[new o.ClassMethod('someMethod', [], [callSomeMethod])])))
.toEqual([
'function SomeClass() {', '}', 'SomeClass.prototype.someMethod = function() {',

View File

@ -52,7 +52,7 @@ export function main() {
.addMapping(3, 'a.js', 5, 2);
// Generated with https://sokra.github.io/source-map-visualization using a TS source map
expect(map.toJSON().mappings)
expect(map.toJSON() !.mappings)
.toEqual(
'AAAA,IAAM,CAAC,GAAe,CAAC,CAAC;AACxB,IAAM,CAAC,GAAG,CAAC,CAAC;AAEZ,EAAE,CAAC,OAAO,CAAC,UAAA,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC,CAAC,CAAA');
});
@ -64,7 +64,7 @@ export function main() {
.addSource('url.ts', null)
.addLine()
.addMapping(0, 'inline.ts', 0, 0)
.toJSON();
.toJSON() !;
expect(map.file).toEqual('out.js');
expect(map.sources).toEqual(['inline.ts', 'url.ts']);
@ -113,7 +113,7 @@ export function main() {
it('should throw when adding segments without column', () => {
expect(() => {
new SourceMapGenerator('out.js').addSource('in.js').addLine().addMapping(null);
new SourceMapGenerator('out.js').addSource('in.js').addLine().addMapping(null !);
}).toThrowError('The column in the generated code must be provided');
});

View File

@ -17,7 +17,8 @@ export interface SourceLocation {
}
export function originalPositionFor(
sourceMap: SourceMap, genPosition: {line: number, column: number}): SourceLocation {
sourceMap: SourceMap,
genPosition: {line: number | null, column: number | null}): SourceLocation {
const smc = new SourceMapConsumer(sourceMap);
// Note: We don't return the original object as it also contains a `name` property
// which is always null and we don't want to include that in our assertions...
@ -25,7 +26,7 @@ export function originalPositionFor(
return {line, column, source};
}
export function extractSourceMap(source: string): SourceMap {
export function extractSourceMap(source: string): SourceMap|null {
let idx = source.lastIndexOf('\n//#');
if (idx == -1) return null;
const smComment = source.slice(idx).trim();

View File

@ -23,8 +23,8 @@ class SimpleJsImportGenerator implements ImportResolver {
fileNameToModuleName(importedUrlStr: string, moduleUrlStr: string): string {
return importedUrlStr;
}
getImportAs(symbol: StaticSymbol): StaticSymbol { return null; }
getTypeArity(symbol: StaticSymbol): number /*|null*/ { return null; }
getImportAs(symbol: StaticSymbol): StaticSymbol|null { return null; }
getTypeArity(symbol: StaticSymbol): number|null { return null; }
}
export function main() {
@ -44,12 +44,12 @@ export function main() {
});
function emitSourceMap(
stmt: o.Statement | o.Statement[], exportedVars: string[] = null,
stmt: o.Statement | o.Statement[], exportedVars: string[] | null = null,
preamble?: string): SourceMap {
const stmts = Array.isArray(stmt) ? stmt : [stmt];
const source = emitter.emitStatements(
someSourceFilePath, someGenFilePath, stmts, exportedVars || [], preamble);
return extractSourceMap(source);
return extractSourceMap(source) !;
}
describe('source maps', () => {

View File

@ -30,8 +30,8 @@ class SimpleJsImportGenerator implements ImportResolver {
fileNameToModuleName(importedUrlStr: string, moduleUrlStr: string): string {
return importedUrlStr;
}
getImportAs(symbol: StaticSymbol): StaticSymbol { return null; }
getTypeArity(symbol: StaticSymbol): number /*|null*/ { return null; }
getImportAs(symbol: StaticSymbol): StaticSymbol|null { return null; }
getTypeArity(symbol: StaticSymbol): number|null { return null; }
}
export function main() {
@ -47,11 +47,11 @@ export function main() {
beforeEach(() => {
importResolver = new SimpleJsImportGenerator();
emitter = new TypeScriptEmitter(importResolver);
someVar = o.variable('someVar');
someVar = o.variable('someVar', null, null);
});
function emitStmt(
stmt: o.Statement | o.Statement[], exportedVars: string[] = null,
stmt: o.Statement | o.Statement[], exportedVars: string[] | null = null,
preamble?: string): string {
const stmts = Array.isArray(stmt) ? stmt : [stmt];
const source = emitter.emitStatements(
@ -310,31 +310,32 @@ export function main() {
it('should support declaring classes', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [
]))).toEqual(['class SomeClass {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, []), ['SomeClass']))
expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, []), ['SomeClass']))
.toEqual(['export class SomeClass {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null, [
expect(emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null !, [
]))).toEqual(['class SomeClass extends SomeSuperClass {', '}'].join('\n'));
});
it('should support declaring constructors', () => {
const superCall = o.SUPER_EXPR.callFn([o.variable('someParam')]).toStmt();
expect(emitStmt(
new o.ClassStmt('SomeClass', null, [], [], new o.ClassMethod(null, [], []), [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null !, [], [], new o.ClassMethod(null !, [], []), [])))
.toEqual(['class SomeClass {', ' constructor() {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [],
new o.ClassMethod(null, [new o.FnParam('someParam', o.INT_TYPE)], []), [])))
'SomeClass', null !, [], [],
new o.ClassMethod(null !, [new o.FnParam('someParam', o.INT_TYPE)], []), [])))
.toEqual(
['class SomeClass {', ' constructor(someParam:number) {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], new o.ClassMethod(null, [], [superCall]), [])))
'SomeClass', null !, [], [], new o.ClassMethod(null !, [], [superCall]), [])))
.toEqual([
'class SomeClass {', ' constructor() {', ' super(someParam);', ' }', '}'
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], new o.ClassMethod(null, [], [callSomeMethod]), [])))
expect(
emitStmt(new o.ClassStmt(
'SomeClass', null !, [], [], new o.ClassMethod(null !, [], [callSomeMethod]), [])))
.toEqual([
'class SomeClass {', ' constructor() {', ' this.someMethod();', ' }', '}'
].join('\n'));
@ -342,56 +343,57 @@ export function main() {
it('should support declaring fields', () => {
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [new o.ClassField('someField')], [], null, [])))
'SomeClass', null !, [new o.ClassField('someField')], [], null !, [])))
.toEqual(['class SomeClass {', ' someField:any;', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [new o.ClassField('someField', o.INT_TYPE)], [], null, [])))
expect(
emitStmt(new o.ClassStmt(
'SomeClass', null !, [new o.ClassField('someField', o.INT_TYPE)], [], null !, [])))
.toEqual(['class SomeClass {', ' someField:number;', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null,
[new o.ClassField('someField', o.INT_TYPE, [o.StmtModifier.Private])], [], null,
[])))
'SomeClass', null !,
[new o.ClassField('someField', o.INT_TYPE, [o.StmtModifier.Private])], [],
null !, [])))
.toEqual(['class SomeClass {', ' /*private*/ someField:number;', '}'].join('\n'));
});
it('should support declaring getters', () => {
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [])], null, [])))
'SomeClass', null !, [], [new o.ClassGetter('someGetter', [])], null !, [])))
.toEqual(['class SomeClass {', ' get someGetter():any {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [], o.INT_TYPE)], null,
[])))
'SomeClass', null !, [], [new o.ClassGetter('someGetter', [], o.INT_TYPE)],
null !, [])))
.toEqual(['class SomeClass {', ' get someGetter():number {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [callSomeMethod])], null,
[])))
'SomeClass', null !, [], [new o.ClassGetter('someGetter', [callSomeMethod])],
null !, [])))
.toEqual([
'class SomeClass {', ' get someGetter():any {', ' this.someMethod();', ' }', '}'
].join('\n'));
expect(
emitStmt(new o.ClassStmt(
'SomeClass', null, [],
[new o.ClassGetter('someGetter', [], null, [o.StmtModifier.Private])], null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null !, [],
[new o.ClassGetter('someGetter', [], null !, [o.StmtModifier.Private])], null !,
[])))
.toEqual(
['class SomeClass {', ' private get someGetter():any {', ' }', '}'].join('\n'));
});
it('should support methods', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [
new o.ClassMethod('someMethod', [], [])
]))).toEqual(['class SomeClass {', ' someMethod():void {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [
new o.ClassMethod('someMethod', [], [], o.INT_TYPE)
]))).toEqual(['class SomeClass {', ' someMethod():number {', ' }', '}'].join('\n'));
expect(
emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
'SomeClass', null !, [], [], null !,
[new o.ClassMethod('someMethod', [new o.FnParam('someParam', o.INT_TYPE)], [])])))
.toEqual([
'class SomeClass {', ' someMethod(someParam:number):void {', ' }', '}'
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
'SomeClass', null !, [], [], null !,
[new o.ClassMethod('someMethod', [], [callSomeMethod])])))
.toEqual([
'class SomeClass {', ' someMethod():void {', ' this.someMethod();', ' }', '}'
@ -453,7 +455,7 @@ export function main() {
it('should support combined types', () => {
const writeVarExpr = o.variable('a').set(o.NULL_EXPR);
expect(emitStmt(writeVarExpr.toDeclStmt(new o.ArrayType(null))))
expect(emitStmt(writeVarExpr.toDeclStmt(new o.ArrayType(null !))))
.toEqual('var a:any[] = (null as any);');
expect(emitStmt(writeVarExpr.toDeclStmt(new o.ArrayType(o.INT_TYPE))))
.toEqual('var a:number[] = (null as any);');

View File

@ -16,7 +16,7 @@ export function main() {
beforeEach(() => { resourceLoader = new MockResourceLoader(); });
function expectResponse(
request: Promise<string>, url: string, response: string, done: () => void = null) {
request: Promise<string>, url: string, response: string, done: () => void = null !) {
function onResponse(text: string): string {
if (response === null) {
throw `Unexpected response ${url} -> ${text}`;
@ -52,7 +52,7 @@ export function main() {
it('should return an error from the definitions',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const url = '/foo';
const response: string = null;
const response: string = null !;
resourceLoader.when(url, response);
expectResponse(resourceLoader.get(url), url, response, () => async.done());
resourceLoader.flush();
@ -70,7 +70,7 @@ export function main() {
it('should return an error from the expectations',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const url = '/foo';
const response: string = null;
const response: string = null !;
resourceLoader.expect(url, response);
expectResponse(resourceLoader.get(url), url, response, () => async.done());
resourceLoader.flush();

View File

@ -113,7 +113,7 @@ export function main() {
}
resourceLoader.spy('get').and.callFake(() => Promise.resolve('hello'));
let ngModuleFactory: NgModuleFactory<any>;
let ngModuleFactory: NgModuleFactory<any> = undefined !;
compiler.compileModuleAsync(SomeModule).then((f) => ngModuleFactory = f);
tick();
expect(ngModuleFactory.moduleType).toBe(SomeModule);

View File

@ -185,7 +185,8 @@ If 'onAnything' is a directive input, make sure the directive is imported by the
if (browserDetection.isChromeDesktop) {
it('generate a new schema', () => {
let schema = '\n';
extractSchema().forEach((props, name) => { schema += `'${name}|${props.join(',')}',\n`; });
extractSchema() !.forEach(
(props, name) => { schema += `'${name}|${props.join(',')}',\n`; });
// Uncomment this line to see:
// the generated schema which can then be pasted to the DomElementSchemaRegistry
// console.log(schema);

View File

@ -39,7 +39,7 @@ const MISSING_FROM_CHROME: {[el: string]: string[]} = {
const _G: any = global;
const document: any = typeof _G['document'] == 'object' ? _G['document'] : null;
export function extractSchema(): Map<string, string[]> {
export function extractSchema(): Map<string, string[]>|null {
if (!document) return null;
const SVGGraphicsElement = _G['SVGGraphicsElement'];
if (!SVGGraphicsElement) return null;
@ -120,7 +120,7 @@ function assertNoMissingTags(descMap: Map<string, string[]>): void {
function extractRecursiveProperties(
visited: {[name: string]: boolean}, descMap: Map<string, string[]>, type: Function): string {
const name = extractName(type);
const name = extractName(type) !;
if (visited[name]) {
return name;
@ -140,7 +140,7 @@ function extractRecursiveProperties(
extractRecursiveProperties(visited, descMap, type.prototype.__proto__.constructor);
}
let instance: HTMLElement = null;
let instance: HTMLElement|null = null;
name.split(',').forEach(tagName => {
instance = type['name'].startsWith('SVG') ?
document.createElementNS('http://www.w3.org/2000/svg', tagName.replace(SVG_PREFIX, '')) :
@ -176,7 +176,7 @@ function extractProperties(
const fullName = name + (superName ? '^' + superName : '');
const props: string[] = descMap.has(fullName) ? descMap.get(fullName) : [];
const props: string[] = descMap.has(fullName) ? descMap.get(fullName) ! : [];
const prototype = type.prototype;
const keys = Object.getOwnPropertyNames(prototype);
@ -199,7 +199,7 @@ function extractProperties(
descMap.set(fullName, type === Node ? props.filter(p => p != '%nodeValue') : props);
}
function extractName(type: Function): string {
function extractName(type: Function): string|null {
let name = type['name'];
switch (name) {

View File

@ -21,7 +21,7 @@ export function main() {
beforeEach(() => {
reset();
s1 = s2 = s3 = s4 = null;
s1 = s2 = s3 = s4 = null !;
selectableCollector =
(selector: CssSelector, context: any) => { matched.push(selector, context); };
matcher = new SelectorMatcher();
@ -128,7 +128,7 @@ export function main() {
const elementSelector = new CssSelector();
const element = el('<div attr></div>');
const empty = getDOM().getAttribute(element, 'attr');
const empty = getDOM().getAttribute(element, 'attr') !;
elementSelector.addAttribute('some-decor', empty);
matcher.match(elementSelector, selectableCollector);
expect(matched).toEqual([s1[0], 1]);

View File

@ -103,7 +103,7 @@ export function main() {
() => { expect(isStyleUrlResolvable('package:someUrl.css')).toBe(true); });
it('should not resolve empty urls', () => {
expect(isStyleUrlResolvable(null)).toBe(false);
expect(isStyleUrlResolvable(null !)).toBe(false);
expect(isStyleUrlResolvable('')).toBe(false);
});

View File

@ -89,14 +89,14 @@ export function main() {
describe('packages', () => {
it('should resolve a url based on the application package', () => {
resolver = new UrlResolver('my_packages_dir');
expect(resolver.resolve(null, 'package:some/dir/file.txt'))
expect(resolver.resolve(null !, 'package:some/dir/file.txt'))
.toEqual('my_packages_dir/some/dir/file.txt');
expect(resolver.resolve(null, 'some/dir/file.txt')).toEqual('some/dir/file.txt');
expect(resolver.resolve(null !, 'some/dir/file.txt')).toEqual('some/dir/file.txt');
});
it('should contain a default value of "/" when nothing is provided',
inject([UrlResolver], (resolver: UrlResolver) => {
expect(resolver.resolve(null, 'package:file')).toEqual('/file');
expect(resolver.resolve(null !, 'package:file')).toEqual('/file');
}));
it('should resolve a package value when present within the baseurl', () => {

View File

@ -15,7 +15,7 @@ export function main() {
it('async value should default to Promise.resolve(syncValue)', fakeAsync(() => {
const syncValue = {};
const sar = new SyncAsyncResult(syncValue);
sar.asyncResult.then((v: any) => expect(v).toBe(syncValue));
sar.asyncResult !.then((v: any) => expect(v).toBe(syncValue));
}));
});