/
MochaTestRunner.ts
179 lines (161 loc) · 6.4 KB
/
MochaTestRunner.ts
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
import * as path from 'path';
import { StrykerOptions } from '@stryker-mutator/api/core';
import { Logger } from '@stryker-mutator/api/logging';
import { commonTokens, tokens } from '@stryker-mutator/api/plugin';
import { RunResult, RunStatus, TestRunner } from '@stryker-mutator/api/test_runner';
import { propertyPath } from '@stryker-mutator/util';
import { MochaOptions, MochaRunnerOptions } from '../src-generated/mocha-runner-options';
import LibWrapper from './LibWrapper';
import { StrykerMochaReporter } from './StrykerMochaReporter';
import { evalGlobal } from './utils';
import { MochaRunnerWithStrykerOptions } from './MochaRunnerWithStrykerOptions';
const DEFAULT_TEST_PATTERN = 'test/**/*.js';
export class MochaTestRunner implements TestRunner {
private testFileNames: string[];
private readonly mochaOptions: MochaOptions;
private rootHooks: any;
public static inject = tokens(commonTokens.logger, commonTokens.sandboxFileNames, commonTokens.options);
constructor(private readonly log: Logger, private readonly allFileNames: readonly string[], options: StrykerOptions) {
this.mochaOptions = (options as MochaRunnerWithStrykerOptions).mochaOptions;
StrykerMochaReporter.log = log;
}
public async init(): Promise<void> {
if (LibWrapper.handleFiles) {
this.log.debug("Mocha >= 6 detected. Using mocha's `handleFiles` to load files");
this.testFileNames = this.mocha6DiscoverFiles(LibWrapper.handleFiles);
} else {
this.log.debug('Mocha < 6 detected. Using custom logic to discover files');
this.testFileNames = this.legacyDiscoverFiles();
}
await this.additionalRequires();
}
private mocha6DiscoverFiles(handleFiles: (options: MochaOptions) => string[]): string[] {
const originalProcessExit = process.exit;
try {
// process.exit unfortunate side effect: https://github.com/mochajs/mocha/blob/07ea8763c663bdd3fe1f8446cdb62dae233f4916/lib/cli/run-helpers.js#L174
(process as any).exit = () => {};
const files = handleFiles(this.mochaOptions);
return files;
} finally {
process.exit = originalProcessExit;
}
}
private legacyDiscoverFiles(): string[] {
const globPatterns = this.mochaFileGlobPatterns();
const globPatternsAbsolute = globPatterns.map((glob) => path.resolve(glob));
const fileNames = LibWrapper.multimatch(this.allFileNames.slice(), globPatternsAbsolute);
if (fileNames.length) {
this.log.debug(`Using files: ${JSON.stringify(fileNames, null, 2)}`);
} else {
this.log.debug(`Tried ${JSON.stringify(globPatternsAbsolute, null, 2)} on files: ${JSON.stringify(this.allFileNames, null, 2)}.`);
throw new Error(
`[${MochaTestRunner.name}] No files discovered (tried pattern(s) ${JSON.stringify(
globPatterns,
null,
2
)}). Please specify the files (glob patterns) containing your tests in ${propertyPath<MochaRunnerOptions>(
'mochaOptions',
'spec'
)} in your config file.`
);
}
return fileNames;
}
private mochaFileGlobPatterns(): string[] {
// Use both `spec` as `files`
const globPatterns: string[] = [];
if (this.mochaOptions.spec) {
globPatterns.push(...this.mochaOptions.spec);
}
if (typeof this.mochaOptions.files === 'string') {
// `files` if for backward compat
globPatterns.push(this.mochaOptions.files);
} else if (this.mochaOptions.files) {
globPatterns.push(...this.mochaOptions.files);
}
if (!globPatterns.length) {
globPatterns.push(DEFAULT_TEST_PATTERN);
}
return globPatterns;
}
public run({ testHooks }: { testHooks?: string }): Promise<RunResult> {
return new Promise<RunResult>((resolve, reject) => {
try {
this.purgeFiles();
const mocha = new LibWrapper.Mocha({ reporter: StrykerMochaReporter as any, bail: true, rootHooks: this.rootHooks } as Mocha.MochaOptions);
this.configure(mocha);
this.addTestHooks(mocha, testHooks);
this.addFiles(mocha);
try {
mocha.run(() => {
const reporter = StrykerMochaReporter.currentInstance;
if (reporter) {
const result: RunResult = reporter.runResult;
resolve(result);
} else {
const errorMsg = 'The StrykerMochaReporter was not instantiated properly. Could not retrieve the RunResult.';
this.log.error(errorMsg);
resolve({
errorMessages: [errorMsg],
status: RunStatus.Error,
tests: [],
});
}
});
} catch (error) {
resolve({
errorMessages: [error],
status: RunStatus.Error,
tests: [],
});
}
} catch (error) {
this.log.error(error);
reject(error);
}
});
}
private purgeFiles() {
this.allFileNames.forEach((fileName) => delete require.cache[fileName]);
}
private addFiles(mocha: Mocha) {
this.testFileNames.forEach((fileName) => {
mocha.addFile(fileName);
});
}
private addTestHooks(mocha: Mocha, testHooks: string | undefined): void {
if (testHooks) {
const suite = (mocha as any).suite;
suite.emit('pre-require', global, '', mocha);
suite.emit('require', evalGlobal(testHooks), '', mocha);
suite.emit('post-require', global, '', mocha);
}
}
private configure(mocha: Mocha) {
const options = this.mochaOptions;
function setIfDefined<T>(value: T | undefined, operation: (input: T) => void) {
if (typeof value !== 'undefined') {
operation.apply(mocha, [value]);
}
}
if (options) {
setIfDefined(options['async-only'], (asyncOnly) => asyncOnly && mocha.asyncOnly());
setIfDefined(options.timeout, mocha.timeout);
setIfDefined(options.ui, mocha.ui);
setIfDefined(options.grep, mocha.grep);
}
}
private async additionalRequires() {
if (this.mochaOptions.require) {
if (LibWrapper.handleRequires) {
const rawRootHooks = await LibWrapper.handleRequires(this.mochaOptions.require);
if (rawRootHooks) {
this.rootHooks = await LibWrapper.loadRootHooks!(rawRootHooks);
}
} else {
const modulesToRequire = this.mochaOptions.require.map((moduleName) => (moduleName.startsWith('.') ? path.resolve(moduleName) : moduleName));
modulesToRequire.forEach(LibWrapper.require);
}
}
}
}