Skip to content

Commit 647d7bd

Browse files
devversionmhevery
authored andcommitted
refactor: fix typescript strict flag failures in all tests (angular#30993)
Fixes all TypeScript failures caused by enabling the `--strict` flag for test source files. We also want to enable the strict options for tests as the strictness enforcement improves the overall codehealth, unveiled common issues and additionally it allows us to enable `strict` in the `tsconfig.json` that is picked up by IDE's. PR Close angular#30993
1 parent 69a612d commit 647d7bd

38 files changed

+256
-203
lines changed

packages/common/http/test/module_spec.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ class ReentrantInterceptor implements HttpInterceptor {
6767
});
6868
});
6969
it('initializes HttpClient properly', done => {
70-
injector.get(HttpClient).get('/test', {responseType: 'text'}).subscribe(value => {
70+
injector.get(HttpClient).get('/test', {responseType: 'text'}).subscribe((value: string) => {
7171
expect(value).toBe('ok!');
7272
done();
7373
});
@@ -76,15 +76,15 @@ class ReentrantInterceptor implements HttpInterceptor {
7676
it('intercepts outbound responses in the order in which interceptors were bound', done => {
7777
injector.get(HttpClient)
7878
.get('/test', {observe: 'response', responseType: 'text'})
79-
.subscribe(value => done());
79+
.subscribe(() => done());
8080
const req = injector.get(HttpTestingController).expectOne('/test') as TestRequest;
8181
expect(req.request.headers.get('Intercepted')).toEqual('A,B');
8282
req.flush('ok!');
8383
});
8484
it('intercepts inbound responses in the right (reverse binding) order', done => {
8585
injector.get(HttpClient)
8686
.get('/test', {observe: 'response', responseType: 'text'})
87-
.subscribe(value => {
87+
.subscribe((value: HttpResponse<string>) => {
8888
expect(value.headers.get('Intercepted')).toEqual('B,A');
8989
done();
9090
});

packages/common/test/pipes/keyvalue_pipe_spec.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,10 @@ describe('defaultComparator', () => {
149149
expect(values.sort(defaultComparator)).toEqual([{key: false, value: 1}, {key: true, value: 3}]);
150150
});
151151
it('should sort numbers as strings in numerical ascending', () => {
152-
const values = [{key: '2', value: 1}, {key: 1, value: 3}];
152+
// We need to cast the values array to "any[]" because the object keys
153+
// have no type overlap and the "Array.sort" expects all keys to have the
154+
// same type when passed to the sort comparator.
155+
const values = [{key: '2', value: 1}, {key: 1, value: 3}] as any[];
153156
expect(values.sort(defaultComparator)).toEqual([{key: 1, value: 3}, {key: '2', value: 1}]);
154157
});
155158
});

packages/compiler-cli/test/compliance/r3_view_compiler_i18n_spec.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,14 @@ const EXTRACT_GENERATED_TRANSLATIONS_REGEXP =
3131
const diff = (a: Set<string>, b: Set<string>): Set<string> =>
3232
new Set([...Array.from(a)].filter(x => !b.has(x)));
3333

34-
const extract =
35-
(from: string, regex: any, transformFn: (match: any[], state?: Set<any>) => any) => {
36-
const result = new Set<any>();
37-
let item;
38-
while ((item = regex.exec(from)) !== null) {
39-
result.add(transformFn(item, result));
40-
}
41-
return result;
42-
};
34+
const extract = (from: string, regex: any, transformFn: (match: any[], state: Set<any>) => any) => {
35+
const result = new Set<any>();
36+
let item;
37+
while ((item = regex.exec(from)) !== null) {
38+
result.add(transformFn(item, result));
39+
}
40+
return result;
41+
};
4342

4443
// verify that we extracted all the necessary translations
4544
// and their ids match the ones extracted via 'ng xi18n'

packages/compiler-cli/test/diagnostics/check_types_spec.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import * as ng from '@angular/compiler-cli';
1010
import * as fs from 'fs';
1111
import * as os from 'os';
1212
import * as path from 'path';
13+
import * as ts from 'typescript';
1314
import {TestSupport, expectNoDiagnostics, setup} from '../test_support';
1415

1516
type MockFiles = {
@@ -52,7 +53,7 @@ describe('ng type checker', () => {
5253
if (!diagnostics || !diagnostics.length) {
5354
throw new Error('Expected a diagnostic error message');
5455
} else {
55-
const matches: (d: ng.Diagnostic) => boolean = typeof message === 'string' ?
56+
const matches: (d: ng.Diagnostic | ts.Diagnostic) => boolean = typeof message === 'string' ?
5657
d => ng.isNgDiagnostic(d)&& d.messageText == message :
5758
d => ng.isNgDiagnostic(d) && message.test(d.messageText);
5859
const matchingDiagnostics = diagnostics.filter(matches) as ng.Diagnostic[];

packages/compiler-cli/test/metadata/bundler_spec.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import * as ts from 'typescript';
1111

1212
import {CompilerHostAdapter, MetadataBundler, MetadataBundlerHost} from '../../src/metadata/bundler';
1313
import {MetadataCollector} from '../../src/metadata/collector';
14-
import {ClassMetadata, MetadataGlobalReferenceExpression, ModuleMetadata} from '../../src/metadata/schema';
14+
import {ClassMetadata, MetadataEntry, MetadataGlobalReferenceExpression, ModuleMetadata} from '../../src/metadata/schema';
1515
import {Directory, MockAotContext, MockCompilerHost} from '../mocks';
1616

1717
describe('compiler host adapter', () => {
@@ -242,7 +242,7 @@ describe('metadata bundler', () => {
242242
const deepIndexMetadata = host.getMetadataFor('/lib/deep/index') !;
243243

244244
// The unbundled metadata should reference symbols using the relative module path.
245-
expect(deepIndexMetadata.metadata['MyClass']).toEqual(jasmine.objectContaining({
245+
expect(deepIndexMetadata.metadata['MyClass']).toEqual(jasmine.objectContaining<MetadataEntry>({
246246
statics: {
247247
ngInjectableDef: {
248248
__symbolic: 'call',
@@ -258,7 +258,7 @@ describe('metadata bundler', () => {
258258
// For the bundled metadata, the "sharedFn" symbol should not be referenced using the
259259
// relative module path (like for unbundled), because the metadata bundle can be stored
260260
// anywhere and it's not guaranteed that the relatively referenced files are present.
261-
expect(bundledMetadata.metadata['MyClass']).toEqual(jasmine.objectContaining({
261+
expect(bundledMetadata.metadata['MyClass']).toEqual(jasmine.objectContaining<MetadataEntry>({
262262
statics: {
263263
ngInjectableDef: {
264264
__symbolic: 'call',

packages/compiler-cli/test/ngtsc/component_indexing_spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88
import {AbsoluteFsPath, resolve} from '@angular/compiler-cli/src/ngtsc/file_system';
99
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
10-
import {AbsoluteSourceSpan, IdentifierKind, TopLevelIdentifier} from '@angular/compiler-cli/src/ngtsc/indexer';
10+
import {AbsoluteSourceSpan, IdentifierKind, IndexedComponent, TopLevelIdentifier} from '@angular/compiler-cli/src/ngtsc/indexer';
1111
import {ParseSourceFile} from '@angular/compiler/src/compiler';
1212

1313
import {NgtscTestEnvironment} from './env';
@@ -43,7 +43,7 @@ runInEachFileSystem(() => {
4343
const [[decl, indexedComp]] = Array.from(indexed.entries());
4444

4545
expect(decl.getText()).toContain('export class TestCmp {}');
46-
expect(indexedComp).toEqual(jasmine.objectContaining({
46+
expect(indexedComp).toEqual(jasmine.objectContaining<IndexedComponent>({
4747
name: 'TestCmp',
4848
selector: 'test-cmp',
4949
file: new ParseSourceFile(componentContent, testSourceFile),

packages/compiler-cli/test/transformers/program_spec.ts

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -83,19 +83,21 @@ describe('ng program', () => {
8383

8484
const originalGetSourceFile = host.getSourceFile;
8585
const cache = new Map<string, ts.SourceFile>();
86-
host.getSourceFile = function(fileName: string): ts.SourceFile {
87-
const sf = originalGetSourceFile.call(host, fileName) as ts.SourceFile;
88-
if (sf) {
89-
if (cache.has(sf.fileName)) {
90-
const oldSf = cache.get(sf.fileName) !;
91-
if (oldSf.getFullText() === sf.getFullText()) {
92-
return oldSf;
86+
host.getSourceFile = function(
87+
fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile |
88+
undefined {
89+
const sf = originalGetSourceFile.call(host, fileName, languageVersion);
90+
if (sf) {
91+
if (cache.has(sf.fileName)) {
92+
const oldSf = cache.get(sf.fileName) !;
93+
if (oldSf.getFullText() === sf.getFullText()) {
94+
return oldSf;
95+
}
96+
}
97+
cache.set(sf.fileName, sf);
9398
}
94-
}
95-
cache.set(sf.fileName, sf);
96-
}
97-
return sf;
98-
};
99+
return sf;
100+
};
99101
return host;
100102
}
101103

@@ -196,12 +198,14 @@ describe('ng program', () => {
196198
const host = ng.createCompilerHost({options});
197199
const originalGetSourceFile = host.getSourceFile;
198200
const fileCache = new Map<string, ts.SourceFile>();
199-
host.getSourceFile = (fileName: string) => {
201+
host.getSourceFile = (fileName: string, languageVersion: ts.ScriptTarget) => {
200202
if (fileCache.has(fileName)) {
201203
return fileCache.get(fileName);
202204
}
203-
const sf = originalGetSourceFile.call(host, fileName);
204-
fileCache.set(fileName, sf);
205+
const sf = originalGetSourceFile.call(host, fileName, languageVersion);
206+
if (sf !== undefined) {
207+
fileCache.set(fileName, sf);
208+
}
205209
return sf;
206210
};
207211

@@ -469,8 +473,8 @@ describe('ng program', () => {
469473

470474
host.writeFile =
471475
(fileName: string, data: string, writeByteOrderMark: boolean,
472-
onError: (message: string) => void|undefined,
473-
sourceFiles: ReadonlyArray<ts.SourceFile>) => {
476+
onError: ((message: string) => void) | undefined,
477+
sourceFiles?: ReadonlyArray<ts.SourceFile>) => {
474478
written.set(fileName, {original: sourceFiles, data});
475479
};
476480
const program = ng.createProgram(
@@ -1095,15 +1099,15 @@ describe('ng program', () => {
10951099
});
10961100
const host = ng.createCompilerHost({options});
10971101
const originalGetSourceFile = host.getSourceFile;
1098-
host.getSourceFile =
1099-
(fileName: string, languageVersion: ts.ScriptTarget,
1100-
onError?: ((message: string) => void) | undefined): ts.SourceFile => {
1101-
// We should never try to load .ngfactory.ts files
1102-
if (fileName.match(/\.ngfactory\.ts$/)) {
1103-
throw new Error(`Non existent ngfactory file: ` + fileName);
1104-
}
1105-
return originalGetSourceFile.call(host, fileName, languageVersion, onError);
1106-
};
1102+
host.getSourceFile = (fileName: string, languageVersion: ts.ScriptTarget,
1103+
onError?: ((message: string) => void) | undefined): ts.SourceFile |
1104+
undefined => {
1105+
// We should never try to load .ngfactory.ts files
1106+
if (fileName.match(/\.ngfactory\.ts$/)) {
1107+
throw new Error(`Non existent ngfactory file: ` + fileName);
1108+
}
1109+
return originalGetSourceFile.call(host, fileName, languageVersion, onError);
1110+
};
11071111
const program = ng.createProgram({rootNames: allRootNames, options, host});
11081112
const structuralErrors = program.getNgStructuralDiagnostics();
11091113
expect(structuralErrors.length).toBe(1);

packages/compiler/test/aot/static_reflector_spec.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ describe('StaticReflector', () => {
2020
function init(
2121
testData: {[key: string]: any} = DEFAULT_TEST_DATA,
2222
decorators: {name: string, filePath: string, ctor: any}[] = [],
23-
errorRecorder?: (error: any, fileName: string) => void, collectorOptions?: CollectorOptions) {
23+
errorRecorder?: (error: any, fileName?: string) => void,
24+
collectorOptions?: CollectorOptions) {
2425
const symbolCache = new StaticSymbolCache();
2526
host = new MockStaticSymbolResolverHost(testData, collectorOptions);
2627
const summaryResolver = new MockSummaryResolver([]);
@@ -618,7 +619,7 @@ describe('StaticReflector', () => {
618619
`;
619620

620621
let error: any = undefined;
621-
init(data, [], (err: any, filePath: string) => {
622+
init(data, [], (err: any, filePath?: string) => {
622623
expect(error).toBeUndefined();
623624
error = err;
624625
});

packages/compiler/test/util_spec.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ import {escapeRegExp, splitAtColon, stringify, utf8Encode} from '../src/util';
7070
['\uDEEE', '\xED\xBB\xAE'],
7171
['\uDFFF', '\xED\xBF\xBF'],
7272
];
73-
tests.forEach(
74-
([input, output]: [string, string]) => { expect(utf8Encode(input)).toEqual(output); });
73+
tests.forEach(([input, output]) => { expect(utf8Encode(input)).toEqual(output); });
7574
});
7675
});
7776

@@ -80,4 +79,4 @@ import {escapeRegExp, splitAtColon, stringify, utf8Encode} from '../src/util';
8079
() => { expect(stringify(Object.create(null))).toEqual('object'); });
8180
});
8281
});
83-
}
82+
}

packages/core/test/acceptance/discover_utils_spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,15 +244,15 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils', () => {
244244
});
245245

246246
it('should work on templates', () => {
247-
const templateComment = Array.from(fixture.nativeElement.childNodes)
247+
const templateComment = Array.from((fixture.nativeElement as HTMLElement).childNodes)
248248
.find((node: ChildNode) => node.nodeType === Node.COMMENT_NODE) !;
249249
const lContext = loadLContext(templateComment);
250250
expect(lContext).toBeDefined();
251251
expect(lContext.native as any).toBe(templateComment);
252252
});
253253

254254
it('should work on ng-container', () => {
255-
const ngContainerComment = Array.from(fixture.nativeElement.childNodes)
255+
const ngContainerComment = Array.from((fixture.nativeElement as HTMLElement).childNodes)
256256
.find(
257257
(node: ChildNode) => node.nodeType === Node.COMMENT_NODE &&
258258
node.textContent === `ng-container`) !;

0 commit comments

Comments
 (0)