UNPKG

2.57 kBJavaScriptView Raw
1const Mocha = require('mocha');
2const camel = require('camelcase');
3const { parent, child } = require('lib/utils/fork');
4const utils = require('lib/utils');
5
6if (module.parent) {
7 module.exports = async (argv, files) => {
8 const mocha = await parent(__filename, { run: [] });
9 try {
10 return await mocha.run(argv, files);
11 } finally {
12 await mocha.end();
13 }
14 };
15} else {
16 child({
17 run: (argv, files) => new Promise((resolve, reject) => {
18 const mocha = load(argv);
19 mocha.files = files.testFiles;
20 for (const require of argv.require) {
21 utils.requireFromCwd(require);
22 }
23 if (argv.all) {
24 for (const sourceFile of Array.from(files.sourceFiles || []).sort()) {
25 utils.requireFromCwd(sourceFile);
26 }
27 }
28 const runner = mocha.run();
29 const failures = [];
30 setTimeout(() => {
31 if (!runner.total) resolve();
32 }, 100);
33 runner.on('fail', (test, error) => {
34 failures.push(error);
35 });
36 runner.on('end', () => {
37 resolve({ failures });
38 });
39 })
40 });
41}
42
43function load(argv = {}) {
44 const opts = getMochaOpts(argv);
45
46 const mocha = new Mocha(opts);
47
48 const ifn = c => f => c && f(c);
49 const opt = new Proxy({}, { get: (_, o) => typeof o === 'string' && (opts[o] || argv[o]) });
50
51 ifn(opt.colors)(c =>
52 mocha.useColors(true));
53
54 ifn(opt.noColors || opt.color === false)(c =>
55 mocha.useColors(false));
56
57 ifn(opt.inlineDiffs)(c =>
58 mocha.useInlineDiffs(true));
59
60 ifn(opt.slow)(c =>
61 mocha.suite.slow(c));
62
63 ifn(opt.timeout)(c =>
64 mocha.suite.timeout(c));
65
66 ifn(opt.noTimeouts)(c =>
67 mocha.enableTimeouts(false));
68
69 ifn(opt.bail || opt.b)(c =>
70 mocha.suite.bail(true));
71
72 ifn(opt.grep)(c =>
73 mocha.grep(c));
74
75 ifn(opt.fgrep)(c =>
76 mocha.fgrep(c));
77
78 ifn(opt.invert)(c =>
79 mocha.invert());
80
81 ifn(opt.checkLeaks)(c =>
82 mocha.checkLeaks());
83
84 ifn(opt.fullTrace)(c =>
85 mocha.fullTrace());
86
87 ifn(opt.growl)(c =>
88 mocha.growl());
89
90 ifn(opt.asyncOnly)(c =>
91 mocha.asyncOnly());
92
93 ifn(opt.delay)(c =>
94 mocha.delay());
95
96 ifn(opt.globals)(c =>
97 mocha.globals(c));
98
99 ifn(opt.retries)(c =>
100 mocha.suit.retries(c));
101
102 ifn(opt.ui)(c =>
103 mocha.ui(c));
104
105 return mocha;
106}
107
108function getMochaOpts(argv) {
109 const opts = {};
110 for (const opt in argv) {
111 if (opt.startsWith('mocha-')) {
112 opts[camel(opt.substr(6))] = argv[opt];
113 } else if (opt.startsWith('mocha')) {
114 opts[opt.charAt(5).toLowerCase() + opt.substr(6)] = argv[opt];
115 }
116 }
117 return opts;
118}