UNPKG

2.02 kBPlain TextView Raw
1import { URL } from 'url';
2import fs from 'fs';
3
4import { MochaOptions } from '../src-generated/mocha-runner-options.js';
5
6const mochaSchema: typeof import('../schema/mocha-runner-options.json') = JSON.parse(
7 fs.readFileSync(new URL('../schema/mocha-runner-options.json', import.meta.url), 'utf-8')
8);
9
10export function serializeMochaLoadOptionsArguments(mochaOptions: MochaOptions): string[] {
11 const args: string[] = [];
12 if (mochaOptions['no-config']) {
13 args.push('--no-config');
14 }
15 if (mochaOptions['no-opts']) {
16 args.push('--no-opts');
17 }
18 if (mochaOptions['no-package']) {
19 args.push('--no-package');
20 }
21 if (mochaOptions.package) {
22 args.push('--package');
23 args.push(mochaOptions.package);
24 }
25 if (mochaOptions.opts) {
26 args.push('--opts');
27 args.push(mochaOptions.opts);
28 }
29 if (mochaOptions.config) {
30 args.push('--config');
31 args.push(mochaOptions.config);
32 }
33 return args;
34}
35
36const SUPPORTED_MOCHA_OPTIONS = Object.freeze(Object.keys(mochaSchema.properties.mochaOptions.properties));
37
38/**
39 * Filter out those config values that are actually useful to run mocha with Stryker
40 * @param rawConfig The raw parsed mocha configuration
41 */
42export function filterConfig(rawConfig: Record<string, any>): Partial<MochaOptions> {
43 const options: Partial<MochaOptions> = {};
44 Object.keys(rawConfig)
45 .filter((rawOption) => SUPPORTED_MOCHA_OPTIONS.some((supportedOption) => rawOption === supportedOption))
46 .forEach((option) => ((options as any)[option] = rawConfig[option]));
47
48 // Config file can also contain positional arguments. They are provided under the `_` key
49 // For example:
50 // When mocha.opts contains "--async-only test/**/*.js", then "test/**/*.js will be the positional argument
51 // We must provide it to mocha as "spec"
52 if (rawConfig._?.length) {
53 if (!options.spec) {
54 options.spec = [];
55 }
56 const specs = options.spec;
57 rawConfig._.forEach((positionalArgument: string) => specs.push(positionalArgument));
58 }
59 return options;
60}