Skip to content
This repository has been archived by the owner on Oct 5, 2021. It is now read-only.

Commit

Permalink
fix: improve type coverage calculation
Browse files Browse the repository at this point in the history
don't count function and class declearations when calculating the type coverage.
Also return the type coverage percentage
  • Loading branch information
urish committed Mar 30, 2018
1 parent 69ef486 commit 77d3193
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './apply-types';
export * from './instrument';
export * from './node-register';
export * from './type-collector';
export * from './type-coverage';
49 changes: 49 additions & 0 deletions src/type-coverage.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,56 @@ describe('type-coverage', () => {
});
expect(typeCoverage(program)).toEqual({
knownTypes: 1,
percentage: 50,
totalTypes: 2,
});
});

it('should not count function declarations when calculating the type coverage', () => {
const input = `
function f() {}
`;

const program = getProgram({
tsCompilerHost: virtualCompilerHost(input, 'c:/test.ts'),
tsConfig: 'tsconfig.json',
tsConfigHost: virtualTsConfigHost({
compilerOptions: {
noImplicitThis: true,
target: 'es2015',
},
include: ['test.ts'],
}),
});
expect(typeCoverage(program)).toEqual({
knownTypes: 0,
percentage: 100,
totalTypes: 0,
});
});

it('should not count class declarations when calculating the type coverage', () => {
const input = `
class MyClass {
constructor () {}
}
`;

const program = getProgram({
tsCompilerHost: virtualCompilerHost(input, 'c:/test.ts'),
tsConfig: 'tsconfig.json',
tsConfigHost: virtualTsConfigHost({
compilerOptions: {
noImplicitThis: true,
target: 'es2015',
},
include: ['test.ts'],
}),
});
expect(typeCoverage(program)).toEqual({
knownTypes: 0,
percentage: 100,
totalTypes: 0,
});
});
});
10 changes: 9 additions & 1 deletion src/type-coverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ export function typeCoverage(program: ts.Program) {

const result = {
knownTypes: 0,
percentage: 100,
totalTypes: 0,
};

function visit(node: ts.Node) {
if (ts.isIdentifier(node)) {
if (
ts.isIdentifier(node) &&
(!node.parent || (!ts.isFunctionDeclaration(node.parent) && !ts.isClassDeclaration(node.parent)))
) {
const type = checker.getTypeAtLocation(node);
if (type) {
result.totalTypes++;
Expand All @@ -27,5 +31,9 @@ export function typeCoverage(program: ts.Program) {
}
}

if (result.totalTypes > 0) {
result.percentage = 100 * result.knownTypes / result.totalTypes;
}

return result;
}

0 comments on commit 77d3193

Please sign in to comment.