Best JavaScript code snippet using stryker-parent
mutation-test-report-helper.ts
Source:mutation-test-report-helper.ts
1import path from 'path';2import { Location, Position, StrykerOptions, MutantTestCoverage, MutantResult, schema, MutantStatus } from '@stryker-mutator/api/core';3import { Logger } from '@stryker-mutator/api/logging';4import { commonTokens, tokens } from '@stryker-mutator/api/plugin';5import { Reporter } from '@stryker-mutator/api/report';6import { I, normalizeFileName, normalizeWhitespaces, type requireResolve } from '@stryker-mutator/util';7import { calculateMutationTestMetrics, MutationTestMetricsResult } from 'mutation-testing-metrics';8import { MutantRunResult, MutantRunStatus, TestResult } from '@stryker-mutator/api/test-runner';9import { CheckStatus, PassedCheckResult, CheckResult } from '@stryker-mutator/api/check';10import { strykerVersion } from '../stryker-package.js';11import { coreTokens } from '../di/index.js';12import { objectUtils } from '../utils/object-utils.js';13import { Project, FileSystem } from '../fs/index.js';14import { TestCoverage } from '../mutants/index.js';15const STRYKER_FRAMEWORK: Readonly<Pick<schema.FrameworkInformation, 'branding' | 'name' | 'version'>> = Object.freeze({16 name: 'StrykerJS',17 version: strykerVersion,18 branding: {19 homepageUrl: 'https://stryker-mutator.io',20 imageUrl:21 "data:image/svg+xml;utf8,%3Csvg viewBox='0 0 1458 1458' xmlns='http://www.w3.org/2000/svg' fill-rule='evenodd' clip-rule='evenodd' stroke-linejoin='round' stroke-miterlimit='2'%3E%3Cpath fill='none' d='M0 0h1458v1458H0z'/%3E%3CclipPath id='a'%3E%3Cpath d='M0 0h1458v1458H0z'/%3E%3C/clipPath%3E%3Cg clip-path='url(%23a)'%3E%3Cpath d='M1458 729c0 402.655-326.345 729-729 729S0 1131.655 0 729C0 326.445 326.345 0 729 0s729 326.345 729 729' fill='%23e74c3c' fill-rule='nonzero'/%3E%3Cpath d='M778.349 1456.15L576.6 1254.401l233-105 85-78.668v-64.332l-257-257-44-187-50-208 251.806-82.793L1076.6 389.401l380.14 379.15c-19.681 367.728-311.914 663.049-678.391 687.599z' fill-opacity='.3'/%3E%3Cpath d='M753.4 329.503c41.79 0 74.579 7.83 97.925 25.444 23.571 18.015 41.69 43.956 55.167 77.097l11.662 28.679 165.733-58.183-14.137-32.13c-26.688-60.655-64.896-108.61-114.191-144.011-49.329-35.423-117.458-54.302-204.859-54.302-50.78 0-95.646 7.376-134.767 21.542-40.093 14.671-74.09 34.79-102.239 60.259-28.84 26.207-50.646 57.06-65.496 92.701-14.718 35.052-22.101 72.538-22.101 112.401 0 72.536 20.667 133.294 61.165 182.704 38.624 47.255 98.346 88.037 179.861 121.291 42.257 17.475 78.715 33.125 109.227 46.994 27.193 12.361 49.294 26.124 66.157 41.751 15.309 14.186 26.497 30.584 33.63 49.258 7.721 20.214 11.16 45.69 11.16 76.402 0 28.021-4.251 51.787-13.591 71.219-8.832 18.374-20.171 33.178-34.523 44.219-14.787 11.374-31.193 19.591-49.393 24.466-19.68 5.359-39.14 7.993-58.69 7.993-29.359 0-54.387-3.407-75.182-10.747-20.112-7.013-37.144-16.144-51.259-27.486-13.618-11.009-24.971-23.766-33.744-38.279-9.64-15.8-17.272-31.924-23.032-48.408l-10.965-31.376-161.669 60.585 10.734 30.124c10.191 28.601 24.197 56.228 42.059 82.748 18.208 27.144 41.322 51.369 69.525 72.745 27.695 21.075 60.904 38.218 99.481 51.041 37.777 12.664 82.004 19.159 132.552 19.159 49.998 0 95.818-8.321 137.611-24.622 42.228-16.471 78.436-38.992 108.835-67.291 30.719-28.597 54.631-62.103 71.834-100.642 17.263-38.56 25.923-79.392 25.923-122.248 0-54.339-8.368-100.37-24.208-138.32-16.29-38.759-38.252-71.661-65.948-98.797-26.965-26.418-58.269-48.835-93.858-67.175-33.655-17.241-69.196-33.11-106.593-47.533-35.934-13.429-65.822-26.601-89.948-39.525-22.153-11.868-40.009-24.21-53.547-37.309-11.429-11.13-19.83-23.678-24.718-37.664-5.413-15.49-7.98-33.423-7.98-53.577 0-40.883 11.293-71.522 37.086-90.539 28.443-20.825 64.985-30.658 109.311-30.658z' fill='%23f1c40f' fill-rule='nonzero'/%3E%3Cpath d='M720 0h18v113h-18zM1458 738v-18h-113v18h113zM720 1345h18v113h-18zM113 738v-18H0v18h113z'/%3E%3C/g%3E%3C/svg%3E",22 },23});24/**25 * A helper class to convert and report mutants that survived or get killed26 */27export class MutationTestReportHelper {28 public static inject = tokens(29 coreTokens.reporter,30 commonTokens.options,31 coreTokens.project,32 commonTokens.logger,33 coreTokens.testCoverage,34 coreTokens.fs,35 coreTokens.requireFromCwd36 );37 constructor(38 private readonly reporter: Required<Reporter>,39 private readonly options: StrykerOptions,40 private readonly project: Project,41 private readonly log: Logger,42 private readonly testCoverage: I<TestCoverage>,43 private readonly fs: I<FileSystem>,44 private readonly requireFromCwd: typeof requireResolve45 ) {}46 public reportCheckFailed(mutant: MutantTestCoverage, checkResult: Exclude<CheckResult, PassedCheckResult>): MutantResult {47 return this.reportOne({48 ...mutant,49 status: this.checkStatusToResultStatus(checkResult.status),50 statusReason: checkResult.reason,51 });52 }53 public reportMutantStatus(mutant: MutantTestCoverage, status: MutantStatus): MutantResult {54 return this.reportOne({55 ...mutant,56 status,57 });58 }59 public reportMutantRunResult(mutant: MutantTestCoverage, result: MutantRunResult): MutantResult {60 // Prune fields used for Stryker bookkeeping61 switch (result.status) {62 case MutantRunStatus.Error:63 return this.reportOne({64 ...mutant,65 status: MutantStatus.RuntimeError,66 statusReason: result.errorMessage,67 });68 case MutantRunStatus.Killed:69 return this.reportOne({70 ...mutant,71 status: MutantStatus.Killed,72 testsCompleted: result.nrOfTests,73 killedBy: result.killedBy,74 statusReason: result.failureMessage,75 });76 case MutantRunStatus.Timeout:77 return this.reportOne({78 ...mutant,79 status: MutantStatus.Timeout,80 statusReason: result.reason,81 });82 case MutantRunStatus.Survived:83 return this.reportOne({84 ...mutant,85 status: MutantStatus.Survived,86 testsCompleted: result.nrOfTests,87 });88 }89 }90 private reportOne(result: MutantResult): MutantResult {91 this.reporter.onMutantTested(result);92 return result;93 }94 private checkStatusToResultStatus(status: Exclude<CheckStatus, CheckStatus.Passed>): MutantStatus {95 switch (status) {96 case CheckStatus.CompileError:97 return MutantStatus.CompileError;98 }99 }100 public async reportAll(results: MutantResult[]): Promise<void> {101 const report = await this.mutationTestReport(results);102 const metrics = calculateMutationTestMetrics(report);103 this.reporter.onAllMutantsTested(results);104 this.reporter.onMutationTestReportReady(report, metrics);105 if (this.options.incremental) {106 await this.fs.mkdir(path.dirname(this.options.incrementalFile), { recursive: true });107 await this.fs.writeFile(this.options.incrementalFile, JSON.stringify(report, null, 2), 'utf-8');108 }109 this.determineExitCode(metrics);110 }111 private determineExitCode(metrics: MutationTestMetricsResult) {112 const mutationScore = metrics.systemUnderTestMetrics.metrics.mutationScore;113 const breaking = this.options.thresholds.break;114 const formattedScore = mutationScore.toFixed(2);115 if (typeof breaking === 'number') {116 if (mutationScore < breaking) {117 this.log.error(`Final mutation score ${formattedScore} under breaking threshold ${breaking}, setting exit code to 1 (failure).`);118 this.log.info('(improve mutation score or set `thresholds.break = null` to prevent this error in the future)');119 objectUtils.setExitCode(1);120 } else {121 this.log.info(`Final mutation score of ${formattedScore} is greater than or equal to break threshold ${breaking}`);122 }123 } else {124 this.log.debug(125 "No breaking threshold configured. Won't fail the build no matter how low your mutation score is. Set `thresholds.break` to change this behavior."126 );127 }128 }129 private async mutationTestReport(results: readonly MutantResult[]): Promise<schema.MutationTestResult> {130 // Mocha, jest and karma use test titles as test ids.131 // This can mean a lot of duplicate strings in the json report.132 // Therefore we remap the test ids here to numbers.133 const testIdMap = new Map([...this.testCoverage.testsById.values()].map((test, index) => [test.id, index.toString()]));134 const remapTestId = (id: string): string => testIdMap.get(id) ?? id;135 const remapTestIds = (ids: string[] | undefined): string[] | undefined => ids?.map(remapTestId);136 return {137 files: await this.toFileResults(results, remapTestIds),138 schemaVersion: '1.0',139 thresholds: this.options.thresholds,140 testFiles: await this.toTestFiles(remapTestId),141 projectRoot: process.cwd(),142 config: this.options,143 framework: {144 ...STRYKER_FRAMEWORK,145 dependencies: this.discoverDependencies(),146 },147 };148 }149 private async toFileResults(150 results: readonly MutantResult[],151 remapTestIds: (ids: string[] | undefined) => string[] | undefined152 ): Promise<schema.FileResultDictionary> {153 const fileResultsByName = new Map<string, schema.FileResult>(154 await Promise.all(155 [...new Set(results.map(({ fileName }) => fileName))].map(async (fileName) => [fileName, await this.toFileResult(fileName)] as const)156 )157 );158 return results.reduce<schema.FileResultDictionary>((acc, mutantResult) => {159 const reportFileName = normalizeReportFileName(mutantResult.fileName);160 const fileResult = acc[reportFileName] ?? (acc[reportFileName] = fileResultsByName.get(mutantResult.fileName)!);161 fileResult.mutants.push(this.toMutantResult(mutantResult, remapTestIds));162 return acc;163 }, {});164 }165 private async toTestFiles(remapTestId: (id: string) => string): Promise<schema.TestFileDefinitionDictionary> {166 const testFilesByName = new Map<string, schema.TestFile>(167 await Promise.all(168 [...new Set([...this.testCoverage.testsById.values()].map(({ fileName }) => fileName))].map(169 async (fileName) => [normalizeReportFileName(fileName), await this.toTestFile(fileName)] as const170 )171 )172 );173 return [...this.testCoverage.testsById.values()].reduce<schema.TestFileDefinitionDictionary>((acc, testResult) => {174 const test = this.toTestDefinition(testResult, remapTestId);175 const reportFileName = normalizeReportFileName(testResult.fileName);176 const testFile = acc[reportFileName] ?? (acc[reportFileName] = testFilesByName.get(reportFileName)!);177 testFile.tests.push(test);178 return acc;179 }, {});180 }181 private async toFileResult(fileName: string): Promise<schema.FileResult> {182 const fileResult: schema.FileResult = {183 language: this.determineLanguage(fileName),184 mutants: [],185 source: '',186 };187 const sourceFile = this.project.files.get(fileName);188 if (sourceFile) {189 fileResult.source = await sourceFile.readOriginal();190 } else {191 this.log.warn(192 normalizeWhitespaces(`File "${fileName}" not found193 in input files, but did receive mutant result for it. This shouldn't happen`)194 );195 }196 return fileResult;197 }198 private async toTestFile(fileName: string | undefined): Promise<schema.TestFile> {199 const testFile: schema.TestFile = { tests: [] };200 if (fileName) {201 const file = this.project.files.get(fileName);202 if (file) {203 testFile.source = await file.readOriginal();204 } else {205 this.log.warn(206 normalizeWhitespaces(`Test file "${fileName}" not found207 in input files, but did receive test result for it. This shouldn't happen.`)208 );209 }210 }211 return testFile;212 }213 private toTestDefinition(test: TestResult, remapTestId: (id: string) => string): schema.TestDefinition {214 return {215 id: remapTestId(test.id),216 name: test.name,217 location: test.startPosition ? { start: this.toPosition(test.startPosition) } : undefined,218 };219 }220 private determineLanguage(name: string): string {221 const ext = path.extname(name).toLowerCase();222 switch (ext) {223 case '.ts':224 case '.tsx':225 return 'typescript';226 case '.html':227 case '.vue':228 return 'html';229 default:230 return 'javascript';231 }232 }233 private toMutantResult(mutantResult: MutantResult, remapTestIds: (ids: string[] | undefined) => string[] | undefined): schema.MutantResult {234 const { fileName, location, killedBy, coveredBy, ...apiMutant } = mutantResult;235 return {236 ...apiMutant,237 killedBy: remapTestIds(killedBy),238 coveredBy: remapTestIds(coveredBy),239 location: this.toLocation(location),240 };241 }242 private toLocation(location: Location): schema.Location {243 return {244 end: this.toPosition(location.end),245 start: this.toPosition(location.start),246 };247 }248 private toPosition(pos: Position): schema.Position {249 return {250 column: pos.column + 1, // convert from 0-based to 1-based251 line: pos.line + 1,252 };253 }254 private discoverDependencies(): schema.Dependencies {255 const discover = (specifier: string) => {256 try {257 return [specifier, (this.requireFromCwd(`${specifier}/package.json`) as { version: string }).version];258 } catch {259 // package does not exist...260 return undefined;261 }262 };263 const dependencies = [264 '@stryker-mutator/mocha-runner',265 '@stryker-mutator/karma-runner',266 '@stryker-mutator/jasmine-runner',267 '@stryker-mutator/jest-runner',268 '@stryker-mutator/typescript-checker',269 'karma',270 'karma-chai',271 'karma-chrome-launcher',272 'karma-jasmine',273 'karma-mocha',274 'mocha',275 'jasmine',276 'jasmine-core',277 'jest',278 'react-scripts',279 'typescript',280 '@angular/cli',281 'webpack',282 'webpack-cli',283 'ts-jest',284 ];285 return dependencies.map(discover).reduce<schema.Dependencies>((acc, dependency) => {286 if (dependency) {287 acc[dependency[0]] = dependency[1];288 }289 return acc;290 }, {});291 }292}293function normalizeReportFileName(fileName: string | undefined) {294 if (fileName) {295 return normalizeFileName(path.relative(process.cwd(), fileName));296 }297 // File name is not required for test files. By default we accumulate tests under the '' key298 return '';...
Using AI Code Generation
1const { testFilesByName } = require('stryker-parent');2const { testFilesByName } = require('stryker-parent');3const { testFilesByName } = require('stryker-parent');4const { testFilesByName } = require('stryker-parent');5const { testFilesByName } = require('stryker-parent');6const { testFilesByName } = require('stryker-parent');7const { testFilesByName } = require('stryker-parent');8const { testFilesByName } = require('stryker-parent');9const { testFilesByName } = require('stryker-parent');10const { testFilesByName } = require('stryker-parent');11const { testFilesByName } = require('stryker-parent');12const { testFilesByName } = require('stryker-parent');13const { testFilesByName } = require('stryker-parent');14const { testFilesByName } = require('stryker-parent');15const { testFilesByName } = require('stryker-parent');16const { testFilesByName } = require('stryker-parent');17const { testFilesByName } = require('stryker-parent');
Using AI Code Generation
1var testFiles = testFilesByName('**/*.js');2var testFiles = testFilesByName('**/*.js');3var testFiles = testFilesByName('**/*.js');4var testFiles = testFilesByName('**/*.js');5var testFiles = testFilesByName('**/*.js');6var testFiles = testFilesByName('**/*.js');7var testFiles = testFilesByName('**/*.js');8var testFiles = testFilesByName('**/*.js');9var testFiles = testFilesByName('**/*.js');10var testFiles = testFilesByName('**/*.js');11var testFiles = testFilesByName('**/*.js');12var testFiles = testFilesByName('**/*.js');13var testFiles = testFilesByName('**/*.js');14var testFiles = testFilesByName('**/*.js');15var testFiles = testFilesByName('**/*.js');
Using AI Code Generation
1const { testFilesByName } = require('stryker-parent');2const files = testFilesByName(['test.js', 'test2.js']);3console.log(files);4const { testFilesByName } = require('stryker-parent');5const files = testFilesByName(['test.js', 'test2.js']);6console.log(files);7const { testFilesByName } = require('stryker-parent');8const files = testFilesByName(['test.js', 'test2.js']);9console.log(files);10const { testFilesByName } = require('stryker-parent');11const files = testFilesByName(['test.js', 'test2.js']);12console.log(files);13const { testFilesByName } = require('stryker-parent');14const files = testFilesByName(['test.js', 'test2.js']);15console.log(files);16const { testFilesByName } = require('stryker-parent');17const files = testFilesByName(['test.js', 'test2.js']);18console.log(files);19const { testFilesByName } = require('stryker-parent');20const files = testFilesByName(['test.js', 'test2.js']);21console.log(files);22const { testFilesByName } = require('stryker-parent');23const files = testFilesByName(['test.js', 'test2.js']);24console.log(files);25const { testFilesByName } = require('stryker-parent');26const files = testFilesByName(['test.js', 'test2.js']);27console.log(files);28const { testFilesByName }
Using AI Code Generation
1var testFiles = testFilesByName('test.js');2var testFiles = testFilesByName('test.js');3var testFiles = testFilesByName('test2.js');4var testFiles = testFilesByName('test3.js');5var testFiles = testFilesByName('test4.js');6var testFiles = testFilesByName('test5.js');7var testFiles = testFilesByName('test6.js');8var testFiles = testFilesByName('test7.js');9var testFiles = testFilesByName('test8.js');10var testFiles = testFilesByName('test9.js');11var testFiles = testFilesByName('test10.js');12var testFiles = testFilesByName('test11.js');13var testFiles = testFilesByName('test12.js');14var testFiles = testFilesByName('test13.js');15var testFiles = testFilesByName('test14.js');16var testFiles = testFilesByName('test15.js');
Using AI Code Generation
1var testFilesByName = require('stryker-parent').testFilesByName;2testFilesByName('test/**/*.js', function(files) {3 console.log(files);4});5var testFilesByName = require('stryker-parent').testFilesByName;6testFilesByName('test/**/*.js', function(files) {7 console.log(files);8});9"jest": {10 },11"jest": {12 },13"jest": {14 },15"jest": {
Using AI Code Generation
1var stryker = require('stryker');2var files = stryker.testFilesByName('test/**/*.js');3console.log(files);4var stryker = require('stryker');5var files = stryker.testFilesByName('test/**/*.js');6console.log(files);7var select = driver.findElement(By.id("id"));8var option = select.findElement(By.css("option[value='value']"));9var value = option.getAttribute('value');10org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"option[value='value']"}11 (Session info: chrome=54.0.2840.71)12 (Driver info: chromedriver=2.24.417418 (4a9a9e0e9d2e1d7d2f5f8b7c5b9f9d7e9b6e8a7b),platform=Windows NT 6.1 SP1 x86_64)13var select = driver.findElement(By.id("id"));14var option = select.findElement(By.css("option[value='value']"));15var value = option.getAttribute('value');16org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector
Using AI Code Generation
1const {testFilesByName} = require('stryker-parent');2testFilesByName('testFilesByName', 'testFilesByName');3const {testFilesByName} = require('stryker-parent');4testFilesByName('testFilesByName', 'testFilesByName');5const {testFilesByName} = require('stryker-parent');6testFilesByName('testFilesByName', 'testFilesByName');7const {testFilesByName} = require('stryker-parent');8testFilesByName('testFilesByName', 'testFilesByName');9const {testFilesByName} = require('stryker-parent');10testFilesByName('testFilesByName', 'testFilesByName');11const {testFilesByName} = require('stryker-parent');12testFilesByName('testFilesByName', 'testFilesByName');13const {testFilesByName} = require('stryker-parent');14testFilesByName('testFilesByName', 'testFilesByName');15const {testFilesByName} = require('stryker-parent');16testFilesByName('testFilesByName', 'testFilesByName');17const {testFilesByName} = require('stryker-parent');18testFilesByName('testFilesByName', 'testFilesByName');19const {testFilesByName} = require('stryker-parent');20testFilesByName('testFilesByName', 'testFilesByName');21const {testFilesByName} = require('stryker-parent');22testFilesByName('testFilesByName', 'testFilesByName');23const {testFilesByName} = require('stryker-parent');24testFilesByName('testFilesByName', 'testFilesByName');
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!!