test: encapsulate mocha into test runner (#3490)

This commit is contained in:
Pavel Feldman 2020-08-14 22:26:16 -07:00 committed by GitHub
parent 5410c30908
commit 73d2dc11d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 26 deletions

View File

@ -18,8 +18,7 @@ const fs = require('fs');
const path = require('path');
const program = require('commander');
const { Runner } = require('./runner');
const Mocha = require('mocha');
const { fixturesUI } = require('./fixturesUI');
const { TestRunner, createTestSuite } = require('./testRunner');
class NullReporter {}
@ -36,26 +35,21 @@ program
.action(async (command) => {
// Collect files
const files = collectFiles(path.join(process.cwd(), command.args[0]), command.args.slice(1));
const rootSuite = new Mocha.Suite('', new Mocha.Context(), true);
const rootSuite = new createTestSuite();
let total = 0;
// Build the test model, suite per file.
for (const file of files) {
const mocha = new Mocha({
const testRunner = new TestRunner(file, {
forbidOnly: command.forbidOnly || undefined,
grep: command.grep,
reporter: NullReporter,
retries: command.retries,
timeout: command.timeout,
ui: fixturesUI.bind(null, true),
trialRun: true,
});
if (command.grep)
mocha.grep(command.grep);
mocha.addFile(file);
mocha.loadFiles();
total += grepTotal(mocha.suite, mocha.options.grep);
rootSuite.addSuite(mocha.suite);
mocha.suite.title = path.basename(file);
total += testRunner.grepTotal();
rootSuite.addSuite(testRunner.suite);
testRunner.suite.title = path.basename(file);
}
if (!total) {
@ -115,12 +109,3 @@ function collectFiles(dir, filters) {
}
return files;
}
function grepTotal(suite, grep) {
let total = 0;
suite.eachTest(test => {
if (grep.test(test.fullTitle()))
total++;
});
return total;
}

View File

@ -36,14 +36,17 @@ class TestRunner extends EventEmitter {
constructor(file, options) {
super();
this.mocha = new Mocha({
ui: fixturesUI.bind(null, options.trialRun),
forbidOnly: options.forbidOnly,
reporter: NullReporter,
timeout: options.timeout,
reporter: NullReporter
ui: fixturesUI.bind(null, options.trialRun),
});
if (options.grep)
this.mocha.grep(options.grep);
this.mocha.addFile(file);
this.mocha.suite.filterOnly();
this.mocha.loadFiles();
this.suite = this.mocha.suite;
this._lastOrdinal = -1;
this._failedWithError = false;
}
@ -79,6 +82,19 @@ class TestRunner extends EventEmitter {
});
await result;
}
grepTotal() {
let total = 0;
this.suite.eachTest(test => {
if (this.mocha.options.grep.test(test.fullTitle()))
total++;
});
return total;
}
}
function createTestSuite() {
return new Mocha.Suite('', new Mocha.Context(), true);
}
function serializeTest(test, origin) {
@ -122,4 +138,4 @@ function serializeError(error) {
return trimCycles(error);
}
module.exports = { TestRunner };
module.exports = { TestRunner, createTestSuite };