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 minifyPrivatesTransformer from '../src/transformer' ; interface TestCase { name : string ; inputFileName : string ; outputFileContent : string ; } const testCasesDir = path . resolve ( __dirname , 'test-cases' ) ; function isDirectory ( filePath ) { return fs . lstatSync ( path . resolve ( testCasesDir , filePath ) ) . isDirectory ( ) ; } function prepareString ( str ) { return str . trim ( ) . replace ( /\r\n/g , '\n' ) ; } function getTestCases ( ) { if ( ! fs . existsSync ( testCasesDir ) || ! fs . lstatSync ( testCasesDir ) . isDirectory ( ) ) { throw new Error ( `${ testCasesDir } folder does not exist` ) ; } return fs . readdirSync ( testCasesDir ) . filter ( ( filePath ) => { return isDirectory ( filePath ) && path . basename ( filePath ) !== 'node_modules' ; } ) . map ( ( directoryName ) => { 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 = { name : directoryName , inputFileName , outputFileContent : prepareString ( fs . readFileSync ( outputFileName , 'utf-8' ) ) , } ; return result ; } ) ; } const formatDiagnosticsHost = { getCanonicalFileName : ( fileName ) => ts . sys . useCaseSensitiveFileNames ? fileName : fileName . toLowerCase ( ) , getCurrentDirectory : ts . sys . getCurrentDirectory , getNewLine : ( ) => ts . sys . newLine , } ; function checkProgramDiagnosticsErrors ( program ) { checkDiagnosticsErrors ( ts . getPreEmitDiagnostics ( program ) ) ; checkDiagnosticsErrors ( program . getDeclarationDiagnostics ( ) ) ; } function checkDiagnosticsErrors ( diagnostics ) { assert . strictEqual ( diagnostics . length , 0 , ts . formatDiagnostics ( diagnostics , formatDiagnosticsHost ) . trim ( ) ) ; } describe ( 'Functional tests' , ( ) => { for ( const testCase of getTestCases ( ) ) { it ( testCase . name , ( ) => { const program = ts . createProgram ( { rootNames : [ testCase . inputFileName ] , options : { target : ts . ScriptTarget . ES5 , experimentalDecorators : true , } , } ) ; checkProgramDiagnosticsErrors ( program ) ; let output ; const transformer = minifyPrivatesTransformer ( program , { prefix : '_private_' , } ) ; program . emit ( undefined , ( fileName , data ) => { output = prepareString ( data ) ; } , undefined , false , { before : [ transformer , ] , } ) ; assert . strictEqual ( output , testCase . outputFileContent , 'Output should be the same as expected' ) ; } ) ; } } ) ;