Skip to content

Commit

Permalink
Introduced tests
Browse files Browse the repository at this point in the history
  • Loading branch information
timocov committed Jun 2, 2019
1 parent e6fb36c commit f8aa536
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 27 deletions.
12 changes: 12 additions & 0 deletions .mocharc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

module.exports = {
require: [
'ts-node/register',
],
extension: ['ts'],
timeout: 10000,
checkLeaks: true,
recursive: true,
diff: true,
};
19 changes: 11 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,22 @@
"url": "https://github.com/timocov/ts-transformer-minify-privates/issues"
},
"homepage": "https://github.com/timocov/ts-transformer-minify-privates#readme",
"devDependencies": {
"@types/nanoid": "~1.2.1",
"tslint": "~5.14.0",
"typescript": "~3.3.4000"
},
"peerDependencies": {
"typescript": ">=2.4.1"
},
"dependencies": {
"nanoid": "~2.0.1"
"devDependencies": {
"@types/chai": "~4.1.7",
"@types/mocha": "~5.2.7",
"@types/node": "^12.0.4",
"chai": "~4.2.0",
"mocha": "~6.1.4",
"ts-node": "~8.2.0",
"tslint": "~5.17.0",
"typescript": "~3.5.1"
},
"scripts": {
"compile": "tsc",
"lint": "tslint --config tslint.json --project tsconfig.json"
"lint": "tslint --config tslint.json --project tsconfig.json",
"test": "mocha tests/functional-test-cases.ts"
}
}
21 changes: 3 additions & 18 deletions src/properties-minifier.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import * as ts from 'typescript';

// tslint:disable-next-line:no-submodule-imports
import generate from 'nanoid/generate';

export interface PropertyMinifierOptions {
/**
* Prefix of generated names (to generate 100% unique names, e.g. '_' or '$')
Expand All @@ -27,11 +24,11 @@ export class PropertiesMinifier {
private readonly namesCache: Map<string, string> = new Map();
private readonly usedNames: Set<string> = new Set();

private currentNameLength: number = 1;
private currentIndex: number = 0;

private readonly options: PropertyMinifierOptions;

public constructor(options: Partial<PropertyMinifierOptions>) {
public constructor(options?: Partial<PropertyMinifierOptions>) {
this.options = { ...defaultOptions, ...options };
}

Expand Down Expand Up @@ -169,21 +166,9 @@ export class PropertiesMinifier {
private getNewName(originalName: string): string {
let result = this.namesCache.get(originalName);
if (result === undefined) {
let attemptsCount = 0;

do {
attemptsCount += 1;

if (attemptsCount === 5) {
attemptsCount = 0;
this.currentNameLength += 1;
}

result = `${this.options.prefix}${generate('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$_', this.currentNameLength)}`;
} while (this.usedNames.has(result));
result = `${this.options.prefix}${this.currentIndex++}`;

this.usedNames.add(result);

this.namesCache.set(originalName, result);
}

Expand Down
102 changes: 102 additions & 0 deletions tests/functional-test-cases.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/// <reference types="node" />

import * as fs from 'fs';
import * as path from 'path';

import * as assert from 'assert';
import { describe, it } from 'mocha';

import * as ts from 'typescript';

import { PropertiesMinifier } from '../src/properties-minifier';

interface TestCase {
name: string;
inputFileName: string;
outputFileContent: string;
}

const testCasesDir = path.resolve(__dirname, 'test-cases');

function isDirectory(filePath: string): boolean {
return fs.lstatSync(path.resolve(testCasesDir, filePath)).isDirectory();
}

function prepareString(str: string): string {
return str.trim().replace(/\r\n/g, '\n');
}

function getTestCases(): TestCase[] {
if (!fs.existsSync(testCasesDir) || !fs.lstatSync(testCasesDir).isDirectory()) {
throw new Error(`${testCasesDir} folder does not exist`);
}

return fs.readdirSync(testCasesDir)
.filter((filePath: string) => {
return isDirectory(filePath) && path.basename(filePath) !== 'node_modules';
})
.map((directoryName: string) => {
const testCaseDir = path.resolve(testCasesDir, directoryName);
const outputFileName = path.resolve(testCaseDir, 'output.js');
const inputFileName = path.relative(process.cwd(), path.resolve(testCaseDir, 'input.ts'));

assert(fs.existsSync(inputFileName), `Input file doesn't exist for ${directoryName}`);
assert(fs.existsSync(outputFileName), `Output file doesn't exist for ${directoryName}`);

const result: TestCase = {
name: directoryName,
inputFileName,
outputFileContent: prepareString(fs.readFileSync(outputFileName, 'utf-8')),
};

return result;
});
}

const formatDiagnosticsHost: ts.FormatDiagnosticsHost = {
getCanonicalFileName: (fileName: string) => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(),
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: () => ts.sys.newLine,
};

function checkProgramDiagnosticsErrors(program: ts.Program): void {
checkDiagnosticsErrors(ts.getPreEmitDiagnostics(program));
checkDiagnosticsErrors(program.getDeclarationDiagnostics());
}

function checkDiagnosticsErrors(diagnostics: ReadonlyArray<ts.Diagnostic>): void {
assert.strictEqual(diagnostics.length, 0, ts.formatDiagnostics(diagnostics, formatDiagnosticsHost).trim());
}

describe('Functional tests', () => {
for (const testCase of getTestCases()) {
const minifier = new PropertiesMinifier();

it(testCase.name, () => {
const program = ts.createProgram({
rootNames: [testCase.inputFileName],
options: {},
});

checkProgramDiagnosticsErrors(program);

let output: string | undefined;

program.emit(
undefined,
(fileName: string, data: string) => {
output = data;
},
undefined,
false,
{
before: [
(context: ts.TransformationContext) => (file: ts.SourceFile) => minifier.visitSourceFile(file, program, context),
],
}
);

assert.strictEqual(output, testCase.outputFileContent, 'Output should be the same as expected');
});
}
});
Empty file added tests/test-cases/README.md
Empty file.
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extends": "./tsconfig.base.json",
"include": [
"src/**/*.ts"
"src/**/*.ts",
"tests/functional-test-cases.ts"
]
}

0 comments on commit f8aa536

Please sign in to comment.