Best JavaScript code snippet using stryker-parent
config-reader.ts
Source:config-reader.ts
1import fs from 'fs';2import path from 'path';3import { pathToFileURL } from 'url';4import { PartialStrykerOptions, StrykerOptions } from '@stryker-mutator/api/core';5import { Logger } from '@stryker-mutator/api/logging';6import { commonTokens, tokens } from '@stryker-mutator/api/plugin';7import { deepMerge, I } from '@stryker-mutator/util';8import { coreTokens } from '../di/index.js';9import { ConfigError } from '../errors.js';10import { fileUtils } from '../utils/file-utils.js';11import { OptionsValidator } from './options-validator.js';12import { SUPPORTED_CONFIG_FILE_BASE_NAMES, SUPPORTED_CONFIG_FILE_EXTENSIONS } from './config-file-formats.js';13export const CONFIG_SYNTAX_HELP = `14Example of how a config file should look:15/**16 * @type {import('@stryker-mutator/api/core').StrykerOptions}17 */18export default {19 // You're options here!20}21Or using commonjs:22/**23 * @type {import('@stryker-mutator/api/core').StrykerOptions}24 */25module.exports = {26 // You're options here!27}28See https://stryker-mutator.io/docs/stryker-js/config-file for more information.`.trim();29export class ConfigReader {30 public static inject = tokens(commonTokens.logger, coreTokens.optionsValidator);31 constructor(private readonly log: Logger, private readonly validator: I<OptionsValidator>) {}32 public async readConfig(cliOptions: PartialStrykerOptions): Promise<StrykerOptions> {33 const options = await this.loadOptionsFromConfigFile(cliOptions);34 // merge the config from config file and cliOptions (precedence)35 deepMerge(options, cliOptions);36 this.validator.validate(options);37 if (this.log.isDebugEnabled()) {38 this.log.debug(`Loaded config: ${JSON.stringify(options, null, 2)}`);39 }40 return options;41 }42 private async loadOptionsFromConfigFile(cliOptions: PartialStrykerOptions): Promise<PartialStrykerOptions> {43 const configFile = await this.findConfigFile(cliOptions.configFile);44 if (!configFile) {45 this.log.info('No config file specified. Running with command line arguments.');46 this.log.info('Use `stryker init` command to generate your config file.');47 return {};48 }49 this.log.debug(`Loading config from ${configFile}`);50 if (path.extname(configFile).toLocaleLowerCase() === '.json') {51 return this.readJsonConfig(configFile);52 } else {53 return this.importJSConfig(configFile);54 }55 }56 private async findConfigFile(configFileName: unknown): Promise<string | undefined> {57 if (typeof configFileName === 'string') {58 if (await fileUtils.exists(configFileName)) {59 return configFileName;60 } else {61 throw new ConfigReaderError('File does not exist!', configFileName);62 }63 }64 for (const file of SUPPORTED_CONFIG_FILE_BASE_NAMES) {65 for (const ext of SUPPORTED_CONFIG_FILE_EXTENSIONS) {66 if (await fileUtils.exists(`${file}${ext}`)) {67 return `${file}${ext}`;68 }69 }70 }71 return undefined;72 }73 private async readJsonConfig(configFile: string): Promise<PartialStrykerOptions> {74 const fileContent = await fs.promises.readFile(configFile, 'utf-8');75 try {76 return JSON.parse(fileContent);77 } catch (err) {78 throw new ConfigReaderError('File contains invalid JSON', configFile, err);79 }80 }81 private async importJSConfig(configFile: string): Promise<PartialStrykerOptions> {82 const importedModule = await this.importJSConfigModule(configFile);83 if (this.hasDefaultExport(importedModule)) {84 const maybeOptions = importedModule.default;85 if (typeof maybeOptions !== 'object') {86 if (typeof maybeOptions === 'function') {87 this.log.fatal(88 `Invalid config file. Exporting a function is no longer supported. Please export an object with your configuration instead, or use a "stryker.conf.json" file.\n${CONFIG_SYNTAX_HELP}`89 );90 } else {91 this.log.fatal(`Invalid config file. It must export an object, found a "${typeof maybeOptions}"!\n${CONFIG_SYNTAX_HELP}`);92 }93 throw new ConfigReaderError('Default export of config file must be an object!', configFile);94 }95 if (!maybeOptions || !Object.keys(maybeOptions).length) {96 this.log.warn(`Stryker options were empty. Did you forget to export options from ${configFile}?`);97 }98 return { ...maybeOptions } as PartialStrykerOptions;99 } else {100 this.log.fatal(`Invalid config file. It is missing a default export. ${describeNamedExports()}\n${CONFIG_SYNTAX_HELP}`);101 throw new ConfigReaderError('Config file must have a default export!', configFile);102 function describeNamedExports() {103 const namedExports: string[] = (typeof importedModule === 'object' && Object.keys(importedModule ?? {})) || [];104 if (namedExports.length === 0) {105 return "In fact, it didn't export anything.";106 } else {107 return `Found named export(s): ${namedExports.map((name) => `"${name}"`).join(', ')}.`;108 }109 }110 }111 }112 private async importJSConfigModule(configFile: string): Promise<unknown> {113 try {114 return await fileUtils.importModule(pathToFileURL(path.resolve(configFile)).toString());115 } catch (err) {116 throw new ConfigReaderError('Error during import', configFile, err);117 }118 }119 private hasDefaultExport(importedModule: unknown): importedModule is { default: unknown } {120 return importedModule && typeof importedModule === 'object' && 'default' in importedModule ? true : false;121 }122}123export class ConfigReaderError extends ConfigError {124 constructor(message: string, configFileName: string, cause?: unknown) {125 super(`Invalid config file "${configFileName}". ${message}`, cause);126 }...
stryker-config-writer.ts
Source:stryker-config-writer.ts
1import { promises as fs } from 'fs';2import { PartialStrykerOptions, StrykerOptions } from '@stryker-mutator/api/core';3import { Logger } from '@stryker-mutator/api/logging';4import { commonTokens, tokens } from '@stryker-mutator/api/plugin';5import { childProcessAsPromised } from '@stryker-mutator/util';6import { fileUtils } from '../utils/file-utils.js';7import { CommandTestRunner } from '../test-runner/command-test-runner.js';8import { SUPPORTED_CONFIG_FILE_BASE_NAMES, SUPPORTED_CONFIG_FILE_EXTENSIONS } from '../config/index.js';9import { PresetConfiguration } from './presets/preset-configuration.js';10import { PromptOption } from './prompt-option.js';11import { initializerTokens } from './index.js';12export class StrykerConfigWriter {13 public static inject = tokens(commonTokens.logger, initializerTokens.out);14 constructor(private readonly log: Logger, private readonly out: typeof console.log) {}15 public async guardForExistingConfig(): Promise<void> {16 for (const file of SUPPORTED_CONFIG_FILE_BASE_NAMES) {17 for (const ext of SUPPORTED_CONFIG_FILE_EXTENSIONS) {18 await this.checkIfConfigFileExists(`${file}${ext}`);19 }20 }21 }22 private async checkIfConfigFileExists(file: string) {23 if (await fileUtils.exists(file)) {24 const msg = `Stryker config file "${file}" already exists in the current directory. Please remove it and try again.`;25 this.log.error(msg);26 throw new Error(msg);27 }28 }29 /**30 * Create config based on the chosen framework and test runner31 * @function32 */33 public write(34 selectedTestRunner: PromptOption,35 buildCommand: PromptOption,36 selectedReporters: PromptOption[],37 selectedPackageManager: PromptOption,38 additionalPiecesOfConfig: Array<Partial<StrykerOptions>>,39 exportAsJson: boolean40 ): Promise<string> {41 const configObject: Partial<StrykerOptions> & { _comment: string } = {42 _comment:43 "This config was generated using 'stryker init'. Please take a look at: https://stryker-mutator.io/docs/stryker-js/configuration/ for more information",44 packageManager: selectedPackageManager.name as 'npm' | 'yarn',45 reporters: selectedReporters.map((rep) => rep.name),46 testRunner: selectedTestRunner.name,47 coverageAnalysis: CommandTestRunner.is(selectedTestRunner.name) ? 'off' : 'perTest',48 };49 // Only write buildCommand to config file if non-empty50 if (buildCommand.name) configObject.buildCommand = buildCommand.name;51 Object.assign(configObject, ...additionalPiecesOfConfig);52 return this.writeStrykerConfig(configObject, exportAsJson);53 }54 /**55 * Create config based on the chosen preset56 * @function57 */58 public async writePreset(presetConfig: PresetConfiguration, exportAsJson: boolean): Promise<string> {59 const config = {60 _comment: `This config was generated using 'stryker init'. Please see the guide for more information: ${presetConfig.guideUrl}`,61 ...presetConfig.config,62 };63 return this.writeStrykerConfig(config, exportAsJson);64 }65 private writeStrykerConfig(config: PartialStrykerOptions, exportAsJson: boolean) {66 if (exportAsJson) {67 return this.writeJsonConfig(config);68 } else {69 return this.writeJsConfig(config);70 }71 }72 private async writeJsConfig(commentedConfig: PartialStrykerOptions) {73 const configFileName = `${SUPPORTED_CONFIG_FILE_BASE_NAMES[0]}.mjs`;74 this.out(`Writing & formatting ${configFileName} ...`);75 const rawConfig = this.stringify(commentedConfig);76 const formattedConfig = `// @ts-check77 /** @type {import('@stryker-mutator/api/core').PartialStrykerOptions} */78 const config = ${rawConfig};79 export default config;`;80 await fs.writeFile(configFileName, formattedConfig);81 try {82 await childProcessAsPromised.exec(`npx prettier --write ${configFileName}`);83 } catch (error) {84 this.log.debug('Prettier exited with error', error);85 this.out('Unable to format stryker.conf.js file for you. This is not a big problem, but it might look a bit messy ð.');86 }87 return configFileName;88 }89 private async writeJsonConfig(commentedConfig: PartialStrykerOptions) {90 const configFileName = `${SUPPORTED_CONFIG_FILE_BASE_NAMES[0]}.json`;91 this.out(`Writing & formatting ${configFileName}...`);92 const typedConfig = {93 $schema: './node_modules/@stryker-mutator/core/schema/stryker-schema.json',94 ...commentedConfig,95 };96 const formattedConfig = this.stringify(typedConfig);97 await fs.writeFile(configFileName, formattedConfig);98 return configFileName;99 }100 private stringify(input: Record<string, unknown>): string {101 return JSON.stringify(input, undefined, 2);102 }...
config-file-formats.ts
Source:config-file-formats.ts
1export const SUPPORTED_CONFIG_FILE_BASE_NAMES = Object.freeze(['stryker.conf', '.stryker.conf'] as const);...
Using AI Code Generation
1const supportedConfigFileBaseNames = require('stryker-parent').SUPPORTED_CONFIG_FILE_BASE_NAMES;2console.log(supportedConfigFileBaseNames);3const supportedConfigFileBaseNames = require('stryker-parent').SUPPORTED_CONFIG_FILE_BASE_NAMES;4console.log(supportedConfigFileBaseNames);5const supportedConfigFileBaseNames = require('stryker-parent').SUPPORTED_CONFIG_FILE_BASE_NAMES;6console.log(supportedConfigFileBaseNames);7const supportedConfigFileBaseNames = require('stryker-parent').SUPPORTED_CONFIG_FILE_BASE_NAMES;8console.log(supportedConfigFileBaseNames);
Using AI Code Generation
1const stryker = require('stryker-parent');2console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);3const stryker = require('stryker');4console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);5const stryker = require('stryker-api');6console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);7const stryker = require('stryker-api/core');8console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);9const stryker = require('stryker-api/config');10console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);11const stryker = require('stryker-api/core');12console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);13const stryker = require('stryker-api/core');14console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);15const stryker = require('stryker-api/core');16console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);17const stryker = require('stryker-api/core');18console.log(stryker.SUPPORTED_CONFIG_FILE_BASE_NAMES);
Using AI Code Generation
1const { SUPPORTED_CONFIG_FILE_BASE_NAMES } = require('@stryker-mutator/core');2console.log(SUPPORTED_CONFIG_FILE_BASE_NAMES);3const { SUPPORTED_CONFIG_FILE_BASE_NAMES } = require('@stryker-mutator/core');4console.log(SUPPORTED_CONFIG_FILE_BASE_NAMES);5const { ConfigReader } = require('@stryker-mutator/core');6const configReader = new ConfigReader();7const config = configReader.readConfig();8const config = configReader.readConfig('json');9const config = configReader.readConfig('conf');10const config = configReader.readConfig('customConfigFile.js');11const config = configReader.readConfig('customConfigFile.js', 'customConfigFile');12const config = configReader.readConfig('customConfigFile');13const config = configReader.readConfig('customConfigFile', 'customConfigFile', 'json');14const config = configReader.readConfig('customConfigFile', 'customConfigFile', 'json');15const config = configReader.readConfig('customConfigFile', 'customConfigFile', 'json');16const config = configReader.readConfig('customConfigFile', 'customConfigFile', 'json');17const config = configReader.readConfig('customConfigFile', 'customConfigFile', 'json');18const config = configReader.readConfig('customConfigFile', 'customConfigFile', 'json');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!