forked from allenhwkim/ngentest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·221 lines (197 loc) · 8.89 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env node
const fs = require('fs');
const path = require('path'); // eslint-disable-line
const yargs = require('yargs');
const ts = require('typescript');
const requireFromString = require('require-from-string');
const glob = require('glob');
const appRoot = require('app-root-path');
const config = require('./ngentest.config');
const Util = require('./src/util.js');
const FuncTestGen = require('./src/func-test-gen.js');
const ComponentTestGen = require('./src/component/component-test-gen.js');
const DirectiveTestGen = require('./src/directive/directive-test-gen.js');
const InjectableTestGen = require('./src/injectable/injectable-test-gen.js');
const PipeTestGen = require('./src/pipe/pipe-test-gen.js');
const ClassTestGen = require('./src/class/class-test-gen.js');
const argv = yargs.usage('Usage: $0 <tsFile> [options]')
.options({
's': { alias: 'spec', describe: 'write the spec file along with source file', type: 'boolean' },
'f': {
alias: 'force',
describe: 'It prints out a new test file, and it does not ask a question when overwrite spec file',
type: 'boolean'
},
'F': {
alias: 'forcePrint',
describe: 'It prints out to console, and it does not ask a question',
type: 'boolean'
},
'm': { alias: 'method', describe: 'Show code only for this method', type: 'string' },
'v': { alias: 'verbose', describe: 'log verbose debug messages', type: 'boolean' },
'framework': { describe: 'test framework, jest or karma', type: 'string' }
})
.example('$0 my.component.ts', 'generate Angular unit test for my.component.ts')
.help('h')
.argv;
Util.DEBUG = argv.verbose;
Util.FRAMEWORK = config.framework || argv.framework;
const tsFile = argv._[0].replace(/\.spec\.ts$/, '.ts');
// const writeToSpec = argv.spec;
if (!(tsFile && fs.existsSync(tsFile))) {
console.error('Error. invalid typescript file. e.g., Usage $0 <tsFile> [options]');
process.exit(1);
}
if (fs.existsSync(path.join(appRoot.path, 'ngentest.config.js'))) {
const userConfig = require(path.join(appRoot.path, 'ngentest.config.js'));
for (var key in userConfig) {
config[key] = userConfig[key];
}
}
Util.DEBUG && console.log(' *** config ***', config);
function getFuncMockData (Klass, funcName, funcType) {
const funcTestGen = new FuncTestGen(Klass, funcName, funcType);
const funcMockData = {
isAsync: funcTestGen.isAsync,
props: {},
params: funcTestGen.getInitialParameters(),
map: {},
globals: {}
};
funcTestGen.getExpressionStatements().forEach((expr, ndx) => {
const code = funcTestGen.classCode.substring(expr.start, expr.end);
Util.DEBUG && console.log(' *** EXPRESSION ***', ndx, code.replace(/\n+/g, '').replace(/\s+/g, ' '));
funcTestGen.setMockData(expr, funcMockData);
});
return funcMockData;
}
function getTestGenerator (tsPath, config) {
const typescript = fs.readFileSync(path.resolve(tsPath), 'utf8');
const angularType = Util.getAngularType(typescript).toLowerCase();
const testGenerator = /* eslint-disable */
angularType === 'component' ? new ComponentTestGen(tsPath, config) :
angularType === 'directive' ? new DirectiveTestGen(tsPath, config) :
angularType === 'service' ? new InjectableTestGen(tsPath, config) :
angularType === 'pipe' ? new PipeTestGen(tsPath, config) :
new ClassTestGen(tsPath, config); /* eslint-enable */
return testGenerator;
}
function getFuncTest(Klass, funcName, funcType, angularType) {
Util.DEBUG &&
console.log('\x1b[36m%s\x1b[0m', `\nPROCESSING #${funcName}`);
const funcMockData = getFuncMockData(Klass, funcName, funcType);
const [allFuncMockJS, asserts] = Util.getFuncMockJS(funcMockData, angularType);
const funcMockJS = [...new Set(allFuncMockJS)];
const funcParamJS = Util.getFuncParamJS(funcMockData.params);
const funcAssertJS = asserts.map(el => `// expect(${el.join('.')}).toHaveBeenCalled()`);
const jsToRun =
funcType === 'set' ? `${angularType}.${funcName} = ${funcParamJS || '{}'}`:
funcType === 'get' ? `const ${funcName} = ${angularType}.${funcName}` :
`${angularType}.${funcName}(${funcParamJS})`;
const itBlockName =
funcType === 'method' ? `should run #${funcName}()` :
funcType === 'get' ? `should run GetterDeclaration #${funcName}` :
funcType === 'set' ? `should run SetterDeclaration #${funcName}` : '';
const asyncStr = funcMockData.isAsync ? 'await ' : '';
return `
it('${itBlockName}', async () => {
${funcMockJS.join(';\n')}${funcMockJS.length ? ';' : ''}
${asyncStr}${jsToRun};
${funcAssertJS.join(';\n')}${funcAssertJS.length ? ';' : ''}
});
`;
}
function run (tsFile) {
try {
const testGenerator = getTestGenerator(tsFile, config);
const typescript = fs.readFileSync(path.resolve(tsFile), 'utf8');
const angularType = Util.getAngularType(typescript).toLowerCase();
const {ejsData} = testGenerator.getData();
ejsData.config = config;
// mockData is set after each statement is being analyzed from getFuncMockData
ejsData.ctorParamJs; // declarition only, will be set from mockData
ejsData.providerMocks; // declarition only, will be set from mockData
ejsData.accessorTests = {}; // declarition only, will be set from mockData
ejsData.functionTests = {}; // declarition only, will be set from mockData
const result = ts.transpileModule(typescript, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
experimentalDecorators: true,
removeComments: true,
target: ts.ScriptTarget.ES2015
}
});
// replace invalid require statements
let replacedOutputText = result.outputText
.replace(/require\("\.(.*)"\)/gm, '{}') // replace require statement to a variable, {}
.replace(/super\(.*\);/gm, '') // remove inheritance code
.replace(/super\./gm, 'this.') // change inheritance call to this call
.replace(/\s+extends\s\S+ {/gm, ' extends Object {') // rchange inheritance to an Object
config.replacements.forEach( ({from,to}) => {
replacedOutputText = replacedOutputText.replace(new RegExp(from, 'gm'), to);
})
const modjule = requireFromString(replacedOutputText);
const Klass = modjule[ejsData.className];
Util.DEBUG &&
console.warn('\x1b[36m%s\x1b[0m', `PROCESSING ${klass.ctor && klass.ctor.name} constructor`);
const ctorMockData = getFuncMockData(Klass, 'constructor', 'constructor');
const ctorParamJs = Util.getFuncParamJS(ctorMockData.params);
ejsData.ctorParamJs = Util.indent(ctorParamJs, ' '.repeat(6)).trim();
ejsData.providerMocks = testGenerator.getProviderMocks(ctorMockData.params);
// for (var key in ejsData.providerMocks) {
// ejsData.providerMocks[key] = Util.indent(ejsData.providerMocks[key]).replace(/\{\s+\}/gm, '{}');
// }
const errors = [];
testGenerator.klassSetters.forEach(setter => {
const setterName = setter.node.name.escapedText;
ejsData.accessorTests[`${setterName} SetterDeclaration`] =
Util.indent(getFuncTest(Klass, setterName, 'set', angularType), ' ');
});
testGenerator.klassGetters.forEach(getter => {
const getterName = getter.node.name.escapedText;
ejsData.accessorTests[`${getterName} GetterDeclaration`] =
Util.indent(getFuncTest(Klass, getterName, 'get', angularType), ' ');
});
testGenerator.klassMethods.forEach(method => {
const methodName = method.node.name.escapedText;
try {
ejsData.functionTests[methodName] =
Util.indent(getFuncTest(Klass, methodName, 'method', angularType), ' ');
} catch (e) {
const msg = ' // '+ e.stack;
const itBlock = `it('should run #${method.name}()', async () => {\n` +
`${msg.replace(/\n/g, '\n // ')}\n` +
` });\n`
ejsData.functionTests[methodName] = itBlock;
errors.push(e);
}
});
// console.log('..................................................................')
// console.log(ejsData)
// console.log('..................................................................')
const generated = testGenerator.getGenerated(ejsData, argv);
generated && testGenerator.writeGenerated(generated, argv);
errors.forEach( e => console.error(e) );
} catch (e) {
console.error(e);
process.exit(1);
}
}
const isDir = fs.lstatSync(tsFile).isDirectory();
if (isDir) {
const files = glob.sync('**/!(*.spec).ts', {cwd: tsFile})
files.forEach(file => {
const includeMatch = config.includeMatch.map(re => file.match(re)).some(e => !!e);
const excludeMatch = config.excludeMatch.map(re => file.match(re)).some(e => !!e);
if (excludeMatch) {
console.log(' *** NOT processing (in excludeMatch)', path.join(tsFile, file));
} else if (includeMatch) {
console.log(' *** processing', path.join(tsFile, file));
run(path.join(tsFile, file));
} else {
console.log(' *** NOT processing (not in includeMatch)', path.join(tsFile, file));
}
});
} else {
run(tsFile);
}