Best JavaScript code snippet using stryker-parent
reporter.ts
Source:reporter.ts
1// https://github.com/mochajs/mocha/pull/1360#issuecomment-4074048312import fs from 'fs-extra';3import {4 utils,5 runConclusionUtils,6 runConclusionInterfaces,7 persist,8 utilGuid,9 sendFailureSuggestionRequestIfApplicable,10} from '@testim/root-cause-core';11import type { Runner, MochaOptions, Test, Stats } from 'mocha';12import Mocha, { reporters } from 'mocha';13import type { RootCauseTestAddonData } from './interfaces';14import debug from 'debug';15import { RunnerResultEntry } from '@testim/root-cause-types';16const debugLogger = debug('testim-root-cause:mocha');17export default class RootCauseMochaReporter implements reporters.Base {18 private runId = utilGuid();19 private runTestResultsDir = utils.constructTestInvocationResultDir(process.cwd(), this.runId);20 private testsResultsMovesCompleted: Array<Promise<void>> = [];21 private rootDir = process.cwd();22 private actualReporter: reporters.Base;23 private testsWithRootCauseResults: Array<{24 mochaTest: Test;25 addonData: RootCauseTestAddonData;26 }> = [];27 private runTestResultsDirCreatePromise = fs.mkdirp(this.runTestResultsDir);28 constructor(public runner: Runner, options: MochaOptions) {29 let ReporterClassToUse: typeof reporters.Base = reporters.Spec;30 const thisForMochaReporterFind: { _reporter?: typeof reporters.Base; options: {} } = {31 options: {},32 };33 // we do that to use the internal behavior of mocha to load the inner reporter34 // https://github.com/mochajs/mocha/blob/v8.1.1/lib/mocha.js#L265-L31635 Mocha.prototype.reporter.call(36 thisForMochaReporterFind,37 options.reporterOptions?.actualReporter ?? '',38 options.reporterOptions39 );40 utils.assertNotNullOrUndefined(thisForMochaReporterFind._reporter);41 ReporterClassToUse = thisForMochaReporterFind._reporter;42 this.actualReporter = new ReporterClassToUse(runner, options);43 runner.on('test end', async (test) => {44 // @ts-ignore45 const rootCauseData: RootCauseTestAddonData | undefined = test.rootCauseData;46 if (!rootCauseData) {47 return;48 }49 this.testsWithRootCauseResults.push({50 mochaTest: test,51 addonData: rootCauseData,52 });53 utils.assertNotNullOrUndefined(test.file);54 const finalTestResultPath = utils.testResultDirFromStartParams({55 description: test.title,56 projectRoot: this.rootDir,57 fullName: test.fullTitle(),58 fullSuitePath: test.file,59 runId: this.runId,60 });61 this.testsResultsMovesCompleted.push(62 (async () => {63 await this.runTestResultsDirCreatePromise;64 try {65 // todo: consider adding explicit copy queue to make operations, so we will have controlled concurrency66 await fs.move(rootCauseData.testIntermediateResultDir, finalTestResultPath, {});67 await fs.remove(rootCauseData.runIntermediateResultsDir);68 } catch (moveError) {69 // unexpected70 // we don't have good recovery from this error71 // debug log it, and ignore72 debugLogger(73 'Error moving test result to final path',74 rootCauseData.startTestParams,75 moveError76 );77 }78 })()79 );80 });81 // eslint-disable-next-line @typescript-eslint/no-this-alias82 const reporterInstance = this;83 runner.on('end', async function () {84 // @ts-ignore85 // eslint-disable-next-line @typescript-eslint/no-this-alias86 const runner: Runner = this;87 debugLogger(`runner end. tests so far: ${reporterInstance.testsWithRootCauseResults.length}`);88 debugLogger(89 `Reporter end event, waiting for tests results to be copied (${reporterInstance.testsResultsMovesCompleted.length})`90 );91 await Promise.all(reporterInstance.testsResultsMovesCompleted);92 debugLogger(`Results copied (${reporterInstance.testsResultsMovesCompleted.length})`);93 const rootCauseRunResults = await runConclusionUtils.readRunResultsDirToMap(94 reporterInstance.runTestResultsDir95 );96 const inputForPrepareRunConclusion = new Map(97 reporterInstance.testsWithRootCauseResults98 .map((test): {99 runner: RunnerResultEntry;100 rootCause: runConclusionInterfaces.RootCauseRunResultEntry;101 } | null => {102 utils.assertNotNullOrUndefined(test.mochaTest.file);103 utils.assertNotNullOrUndefined(test.mochaTest.state);104 const id = utils.testUniqueIdentifierFromStartParams(test.addonData.startTestParams);105 const rootCause = rootCauseRunResults.get(id);106 if (!rootCause) {107 debugLogger('test result dropped, this is a possible bug', { id });108 return null;109 }110 return {111 runner: {112 id: utils.testUniqueIdentifierFromStartParams(test.addonData.startTestParams),113 suiteFilePath: test.mochaTest.file,114 testResult: {115 status: test.mochaTest.state,116 title: test.addonData.startTestParams.description,117 fullName: test.addonData.startTestParams.fullName,118 },119 },120 rootCause,121 };122 })123 .filter(utils.nonNullable)124 .map((e) => [e.runner.id, e])125 );126 const rootCausePath = utils.constructResultDir(reporterInstance.rootDir);127 const startTime = runner.stats?.start;128 utils.assertNotNullOrUndefined(startTime);129 await runConclusionUtils.concludeRun(130 reporterInstance.runId,131 rootCausePath,132 startTime.getTime(),133 inputForPrepareRunConclusion134 );135 try {136 const filesList = await utils.getFilesInDirectoryRecursive(137 reporterInstance.runTestResultsDir138 );139 const failedTestsCount = [...inputForPrepareRunConclusion.values()].filter(140 (t) => t.runner.testResult.status === 'failed'141 ).length;142 await sendFailureSuggestionRequestIfApplicable(failedTestsCount, filesList.length);143 } catch (e) {144 debugLogger(e);145 }146 if (process.env.TESTIM_PERSIST_RESULTS_TO_CLOUD) {147 await persist(reporterInstance.runId, {148 projectRoot: reporterInstance.rootDir,149 resultLabel: (global as any).resultLabels ?? null,150 });151 }152 });153 }154 public get stats(): Stats {155 return this.actualReporter.stats;156 }157 public get failures(): Test[] {158 return this.actualReporter.failures;159 }160 epilogue(): void {161 return this.actualReporter.epilogue();162 }163 public done(failures: number, fn?: ((failures: number) => void) | undefined) {164 if (this.actualReporter.done) {165 return this.actualReporter.done(failures, fn);166 }167 }168}...
plugin-creator.spec.ts
Source:plugin-creator.spec.ts
1import { expect } from 'chai';2import { ClassPlugin, FactoryPlugin, Plugin, PluginKind } from '@stryker-mutator/api/plugin';3import { factory, testInjector } from '@stryker-mutator/test-helpers';4import { coreTokens, PluginCreator } from '../../../src/di/index.js';5describe(PluginCreator.name, () => {6 let sut: PluginCreator;7 let pluginsByKind: Map<PluginKind, Array<Plugin<PluginKind>>>;8 beforeEach(() => {9 pluginsByKind = new Map();10 sut = testInjector.injector.provideValue(coreTokens.pluginsByKind, pluginsByKind).injectClass(PluginCreator);11 });12 it("should create a FactoryPlugin using it's factory method", () => {13 // Arrange14 const expectedReporter = factory.reporter('foo');15 const factoryPlugin: FactoryPlugin<PluginKind.Reporter, []> = {16 kind: PluginKind.Reporter,17 name: 'foo',18 factory() {19 return expectedReporter;20 },21 };22 pluginsByKind.set(PluginKind.Reporter, [factoryPlugin]);23 // Act24 const actualReporter = sut.create(PluginKind.Reporter, 'foo');25 // Assert26 expect(actualReporter).eq(expectedReporter);27 });28 it("should create a ClassPlugin using it's constructor", () => {29 // Arrange30 class FooReporter {}31 const classPlugin: ClassPlugin<PluginKind.Reporter, []> = {32 injectableClass: FooReporter,33 kind: PluginKind.Reporter,34 name: 'foo',35 };36 pluginsByKind.set(PluginKind.Reporter, [classPlugin]);37 // Act38 const actualReporter = sut.create(PluginKind.Reporter, 'foo');39 // Assert40 expect(actualReporter).instanceOf(FooReporter);41 });42 it('should match plugins on name ignore case', () => {43 // Arrange44 const expectedReporter = factory.reporter('bar');45 pluginsByKind.set(PluginKind.Reporter, [46 {47 kind: PluginKind.Reporter,48 name: 'foo',49 factory: factory.reporter,50 },51 {52 kind: PluginKind.Reporter,53 name: 'bar',54 factory() {55 return expectedReporter;56 },57 },58 {59 kind: PluginKind.Reporter,60 name: 'baz',61 factory: factory.reporter,62 },63 ]);64 // Act65 const actualReporter = sut.create(PluginKind.Reporter, 'bAr');66 // Assert67 expect(actualReporter).eq(expectedReporter);68 });69 it('should throw if plugin is not recognized', () => {70 // @ts-expect-error71 const errorPlugin: ClassPlugin<PluginKind.Reporter, []> = {72 kind: PluginKind.Reporter,73 name: 'foo',74 };75 pluginsByKind.set(PluginKind.Reporter, [errorPlugin]);76 expect(() => sut.create(PluginKind.Reporter, 'foo')).throws(77 'Plugin "Reporter:foo" could not be created, missing "factory" or "injectableClass" property.'78 );79 });80 it('should throw if the plugin cannot be found', () => {81 expect(() => sut.create(PluginKind.Checker, 'chess')).throws(82 'Cannot find Checker plugin "chess". In fact, no Checker plugins were loaded. Did you forget to install it?'83 );84 });85 it('should throw if the plugin cannot be found, but other plugins of its kind could', () => {86 pluginsByKind.set(PluginKind.Reporter, [87 { kind: PluginKind.Reporter, factory: factory.reporter, name: 'foo' },88 { kind: PluginKind.Reporter, factory: factory.reporter, name: 'bar' },89 ]);90 expect(() => sut.create(PluginKind.Reporter, 'chess')).throws(91 'Cannot find Reporter plugin "chess". Did you forget to install it? Loaded Reporter plugins were: foo, bar'92 );93 });...
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!!