Best JavaScript code snippet using stryker-parent
karma-test-runner.spec.ts
Source:karma-test-runner.spec.ts
1import { LoggerFactoryMethod } from '@stryker-mutator/api/logging';2import { commonTokens } from '@stryker-mutator/api/plugin';3import { testInjector, assertions, factory, tick } from '@stryker-mutator/test-helpers';4import { expect } from 'chai';5import { TestResults } from 'karma';6import sinon from 'sinon';7import { Task } from '@stryker-mutator/util';8import { DryRunOptions, MutantRunOptions, TestRunnerCapabilities, TestStatus } from '@stryker-mutator/api/test-runner';9import { MutantCoverage } from '@stryker-mutator/api/core';10import { configureKarma } from '../../src/karma-plugins/stryker-karma.conf.js';11import { KarmaTestRunner } from '../../src/karma-test-runner.js';12import { ProjectStarter } from '../../src/starters/project-starter.js';13import { StrykerKarmaSetup } from '../../src-generated/karma-runner-options.js';14import { Browser, KarmaSpec, StrykerReporter } from '../../src/karma-plugins/stryker-reporter.js';15import { TestHooksMiddleware } from '../../src/karma-plugins/test-hooks-middleware.js';16import { karma } from '../../src/karma-wrapper.js';17import { pluginTokens } from '../../src/plugin-tokens.js';18// Unit tests for both the KarmaTestRunner and the StrykerReporter, as they are closely related19describe(KarmaTestRunner.name, () => {20 let projectStarterMock: sinon.SinonStubbedInstance<ProjectStarter>;21 let setGlobalsStub: sinon.SinonStubbedMember<typeof configureKarma.setGlobals>;22 let karmaRunStub: sinon.SinonStubbedMember<typeof karma.runner.run>;23 let getLogger: LoggerFactoryMethod;24 let testHooksMiddlewareMock: sinon.SinonStubbedInstance<TestHooksMiddleware>;25 beforeEach(() => {26 projectStarterMock = { start: sinon.stub() };27 testHooksMiddlewareMock = sinon.createStubInstance(TestHooksMiddleware);28 setGlobalsStub = sinon.stub(configureKarma, 'setGlobals');29 karmaRunStub = sinon.stub(karma.runner, 'run');30 sinon.stub(TestHooksMiddleware, 'instance').value(testHooksMiddlewareMock);31 getLogger = testInjector.injector.resolve(commonTokens.getLogger);32 });33 function createSut() {34 return testInjector.injector.provideValue(pluginTokens.projectStarter, projectStarterMock).injectClass(KarmaTestRunner);35 }36 describe('capabilities', () => {37 it('should communicate reloadEnvironment=true', () => {38 const expectedCapabilities: TestRunnerCapabilities = { reloadEnvironment: true };39 expect(createSut().capabilities()).deep.eq(expectedCapabilities);40 });41 });42 it('should load default setup', () => {43 createSut();44 expect(setGlobalsStub).calledWith({45 getLogger,46 karmaConfig: undefined,47 karmaConfigFile: undefined,48 disableBail: false,49 });50 });51 it('should setup karma from stryker options', () => {52 const expectedSetup: StrykerKarmaSetup = {53 config: {54 basePath: 'foo/bar',55 },56 configFile: 'baz.conf.js',57 projectType: 'angular-cli',58 };59 testInjector.options.karma = expectedSetup;60 testInjector.options.disableBail = true;61 createSut();62 expect(setGlobalsStub).calledWith({63 getLogger,64 karmaConfig: expectedSetup.config,65 karmaConfigFile: expectedSetup.configFile,66 disableBail: true,67 });68 expect(testInjector.logger.warn).not.called;69 });70 describe('init', () => {71 let sut: KarmaTestRunner;72 async function actInit() {73 const initPromise = sut.init();74 StrykerReporter.instance.onBrowsersReady();75 await initPromise;76 }77 beforeEach(async () => {78 sut = createSut();79 StrykerReporter.instance.karmaConfig = await karma.config.parseConfig(null, {}, { promiseConfig: true });80 });81 it('should start karma', async () => {82 projectStarterMock.start.resolves({ exitPromise: new Task<number>().promise });83 await actInit();84 expect(projectStarterMock.start).called;85 });86 it('should reject when karma start rejects', async () => {87 const expected = new Error('karma unavailable');88 projectStarterMock.start.rejects(expected);89 await expect(sut.init()).rejectedWith(expected);90 });91 it('should reject on browser errors', async () => {92 projectStarterMock.start.resolves({ exitPromise: new Task<number>().promise });93 const expected = new Error('karma unavailable');94 const onGoingInit = sut.init();95 StrykerReporter.instance.onBrowserError(createBrowser(), expected);96 await expect(onGoingInit).rejectedWith(expected);97 });98 it('should reject when karma exists during init', async () => {99 const exitTask = new Task<number>();100 projectStarterMock.start.resolves({ exitPromise: exitTask.promise });101 const onGoingInit = sut.init();102 exitTask.resolve(1);103 await expect(onGoingInit).rejectedWith(104 "Karma exited prematurely with exit code 1. Please run stryker with `--logLevel trace` to see the karma logging and figure out what's wrong."105 );106 });107 it('should reject on karma version prior to 6.3.0', async () => {108 sinon.stub(karma, 'VERSION').value('6.2.9');109 await expect(sut.init()).rejectedWith('Your karma version (6.2.9) is not supported. Please install 6.3.0 or higher');110 });111 it('should not reject when disposed early (#3486)', async () => {112 // Arrange113 const exitTask = new Task<number>();114 projectStarterMock.start.resolves({ exitPromise: exitTask.promise });115 const onGoingInit = sut.init();116 // Act117 await sut.dispose();118 exitTask.resolve(0);119 // Assert120 await expect(onGoingInit).not.rejected;121 });122 });123 describe('dryRun', () => {124 let sut: KarmaTestRunner;125 beforeEach(() => {126 sut = createSut();127 karmaRunStub.callsArgOnWith(1, null, 0);128 });129 function actDryRun({130 specResults = [],131 runResults = createKarmaTestResults(),132 options = factory.dryRunOptions(),133 mutantCoverage = factory.mutantCoverage(),134 browserError = undefined,135 }: {136 specResults?: KarmaSpec[];137 runResults?: TestResults;138 options?: DryRunOptions;139 mutantCoverage?: MutantCoverage;140 browserError?: [browser: Browser, error: any] | undefined;141 }) {142 const dryRunPromise = sut.dryRun(options);143 actRun({ browserError, specResults, mutantCoverage, hitCount: undefined, runResults });144 return dryRunPromise;145 }146 it('should report completed specs as test results', async () => {147 const specResults = [148 createKarmaSpec({ id: 'spec1', suite: ['foo'], description: 'should bar', time: 42, success: true }),149 createKarmaSpec({150 id: 'spec2',151 suite: ['bar', 'when baz'],152 description: 'should qux',153 log: ['expected quux to be qux', 'expected length of 1'],154 time: 44,155 success: false,156 }),157 createKarmaSpec({ id: 'spec3', suite: ['quux'], description: 'should corge', time: 45, skipped: true }),158 ];159 const expectedTests = [160 factory.testResult({ id: 'spec1', status: TestStatus.Success, timeSpentMs: 42, name: 'foo should bar' }),161 factory.testResult({162 id: 'spec2',163 status: TestStatus.Failed,164 timeSpentMs: 44,165 name: 'bar when baz should qux',166 failureMessage: 'expected quux to be qux, expected length of 1',167 }),168 factory.testResult({ id: 'spec3', status: TestStatus.Skipped, timeSpentMs: 45, name: 'quux should corge' }),169 ];170 const actualResult = await actDryRun({ specResults });171 assertions.expectCompleted(actualResult);172 expect(actualResult.tests).deep.eq(expectedTests);173 });174 it('should run karma with custom karma configuration', async () => {175 // Arrange176 projectStarterMock.start.resolves({ exitPromise: new Task<number>().promise });177 StrykerReporter.instance.karmaConfig = await karma.config.parseConfig(null, {}, { promiseConfig: true });178 StrykerReporter.instance.karmaConfig.hostname = 'www.localhost.com';179 StrykerReporter.instance.karmaConfig.port = 1337;180 StrykerReporter.instance.karmaConfig.listenAddress = 'www.localhost.com:1337';181 const parseConfigStub = sinon.stub(karma.config, 'parseConfig');182 const expectedRunConfig = { custom: 'config' };183 parseConfigStub.resolves(expectedRunConfig);184 const initPromise = sut.init();185 StrykerReporter.instance.onBrowsersReady();186 await initPromise;187 // Act188 await actDryRun({});189 // Assert190 expect(karmaRunStub).calledWith(expectedRunConfig, sinon.match.func);191 expect(parseConfigStub).calledWithExactly(null, { hostname: 'www.localhost.com', port: 1337, listenAddress: 'www.localhost.com:1337' });192 });193 it('should log when karma run is done', async () => {194 await actDryRun({});195 expect(testInjector.logger.debug).calledWith('karma run done with ', 0);196 });197 it('should clear run results between runs', async () => {198 const firstTestResult = createKarmaSpec({ id: 'spec1', suite: ['foo'], description: 'should bar', time: 42, success: true });199 const expectedTestResult = factory.testResult({ id: 'spec1', status: TestStatus.Success, timeSpentMs: 42, name: 'foo should bar' });200 const actualFirstResult = await actDryRun({ specResults: [firstTestResult] });201 const actualSecondResult = await actDryRun({});202 assertions.expectCompleted(actualFirstResult);203 assertions.expectCompleted(actualSecondResult);204 expect(actualFirstResult.tests).deep.eq([expectedTestResult]);205 expect(actualSecondResult.tests).lengthOf(0);206 });207 it('should configure the coverage analysis in the test hooks middleware', async () => {208 await actDryRun({ options: factory.dryRunOptions({ coverageAnalysis: 'all' }) });209 expect(testHooksMiddlewareMock.configureCoverageAnalysis).calledWithExactly('all');210 });211 it('should add coverage report when the reporter raises the "coverage_report" event', async () => {212 const expectedCoverageReport = factory.mutantCoverage({ static: { '1': 4 } });213 const actualResult = await actDryRun({ mutantCoverage: expectedCoverageReport });214 assertions.expectCompleted(actualResult);215 expect(actualResult.mutantCoverage).eq(expectedCoverageReport);216 });217 it('should add error when the reporter raises the "browser_error" event', async () => {218 const expectedError = 'Global variable undefined';219 const actualResult = await actDryRun({ runResults: createKarmaTestResults({ error: true }), browserError: [createBrowser(), expectedError] });220 assertions.expectErrored(actualResult);221 expect(actualResult.errorMessage).deep.eq(expectedError);222 });223 it('should report state Error when tests where ran and run completed in an error', async () => {224 const actualResult = await actDryRun({225 runResults: createKarmaTestResults({ error: true }),226 specResults: [createKarmaSpec()],227 browserError: [createBrowser(), 'some error'],228 });229 assertions.expectErrored(actualResult);230 });231 });232 describe('mutantRun', () => {233 let sut: KarmaTestRunner;234 function actMutantRun({235 specResults = [],236 runResults = createKarmaTestResults(),237 options = factory.mutantRunOptions(),238 mutantCoverage = factory.mutantCoverage(),239 hitCount = undefined,240 browserError = undefined,241 }: {242 specResults?: KarmaSpec[];243 runResults?: TestResults;244 options?: MutantRunOptions;245 hitCount?: number;246 mutantCoverage?: MutantCoverage;247 browserError?: [browser: Browser, error: any] | undefined;248 }) {249 const promise = sut.mutantRun(options);250 actRun({ specResults, runResults, mutantCoverage, hitCount, browserError });251 return promise;252 }253 beforeEach(() => {254 sut = createSut();255 karmaRunStub.callsArgOn(1, 0);256 });257 it('should configure the mutant run on the middleware', async () => {258 const options = factory.mutantRunOptions({ testFilter: ['foobar'] });259 await actMutantRun({ options });260 expect(testHooksMiddlewareMock.configureMutantRun).calledOnceWithExactly(options);261 });262 it('should correctly report a survived mutant', async () => {263 const result = await actMutantRun({ specResults: [createKarmaSpec({ success: true })] });264 assertions.expectSurvived(result);265 expect(result.nrOfTests).eq(1);266 });267 it('should correctly report a killed mutant', async () => {268 const result = await actMutantRun({ specResults: [createKarmaSpec({ success: true }), createKarmaSpec({ success: false })] });269 assertions.expectKilled(result);270 expect(result.nrOfTests).eq(2);271 });272 it('should report a timeout when the browser disconnects', async () => {273 arrangeLauncherMock();274 const onGoingRun = sut.mutantRun(factory.mutantRunOptions());275 StrykerReporter.instance.onRunStart();276 StrykerReporter.instance.onBrowserError(createBrowser({ id: '42', state: 'DISCONNECTED' }), 'disconnected');277 StrykerReporter.instance.onRunComplete(null, createKarmaTestResults({ disconnected: true }));278 StrykerReporter.instance.onBrowsersReady();279 const result = await onGoingRun;280 assertions.expectTimeout(result);281 expect(result.reason).eq('Browser disconnected during test execution. Karma error: disconnected');282 });283 it('should restart the browser and wait until it is restarted when it gets disconnected (issue #2989)', async () => {284 // Arrange285 const { launcher, karmaServer } = arrangeLauncherMock();286 // Act287 let runCompleted = false;288 const onGoingRun = sut.mutantRun(factory.mutantRunOptions()).then(() => (runCompleted = true));289 StrykerReporter.instance.onRunStart();290 StrykerReporter.instance.onBrowserError(createBrowser({ id: '42', state: 'DISCONNECTED' }), 'disconnected');291 // Assert292 expect(launcher.restart).calledWith('42');293 expect(karmaServer.get).calledWith('launcher');294 StrykerReporter.instance.onRunComplete(null, createKarmaTestResults({ disconnected: true }));295 await tick();296 expect(runCompleted).false;297 StrykerReporter.instance.onBrowsersReady();298 await onGoingRun;299 });300 it('should report a timeout when the hitLimit was reached', async () => {301 const result = await actMutantRun({302 options: factory.mutantRunOptions({ hitLimit: 9 }),303 specResults: [createKarmaSpec({ success: false })],304 hitCount: 10,305 });306 assertions.expectTimeout(result);307 expect(result.reason).contains('Hit limit reached (10/9)');308 });309 it('should reset the hitLimit between runs', async () => {310 const firstResult = await actMutantRun({311 options: factory.mutantRunOptions({ hitLimit: 9 }),312 specResults: [createKarmaSpec({ success: false })],313 hitCount: 10,314 });315 const secondResult = await actMutantRun({316 options: factory.mutantRunOptions({ hitLimit: undefined }),317 specResults: [createKarmaSpec({ success: false })],318 hitCount: 10,319 });320 assertions.expectTimeout(firstResult);321 assertions.expectKilled(secondResult);322 });323 });324 describe('dispose', () => {325 beforeEach(async () => {326 StrykerReporter.instance.karmaConfig = await karma.config.parseConfig(null, {}, { promiseConfig: true });327 });328 it('should not do anything if there is no karma server', async () => {329 const sut = createSut();330 await expect(sut.dispose()).not.rejected;331 });332 it('should stop the karma server', async () => {333 const karmaServerMock = sinon.createStubInstance(karma.Server);334 StrykerReporter.instance.karmaServer = karmaServerMock;335 const sut = createSut();336 await sut.dispose();337 expect(karmaServerMock.stop).called;338 });339 it('should await the exit promise provided at startup', async () => {340 // Arrange341 const sut = createSut();342 const karmaServerMock = sinon.createStubInstance(karma.Server);343 StrykerReporter.instance.karmaServer = karmaServerMock;344 const exitTask = new Task<number>();345 let disposeResolved = false;346 projectStarterMock.start.resolves({ exitPromise: exitTask.promise });347 const initPromise = sut.init();348 StrykerReporter.instance.onBrowsersReady();349 await initPromise;350 // Act351 const onGoingDisposal = sut.dispose().then(() => (disposeResolved = true));352 // Assert353 await tick();354 expect(disposeResolved).false;355 exitTask.resolve(1);356 await onGoingDisposal;357 });358 });359 function actRun({360 specResults,361 runResults,362 mutantCoverage,363 hitCount,364 browserError,365 }: {366 specResults: KarmaSpec[];367 runResults: TestResults;368 mutantCoverage: MutantCoverage;369 hitCount: number | undefined;370 browserError: [browser: Browser, error: any] | undefined;371 }) {372 StrykerReporter.instance.onRunStart();373 specResults.forEach((spec) => StrykerReporter.instance.onSpecComplete(null, spec));374 if (browserError) {375 StrykerReporter.instance.onBrowserError(...browserError);376 }377 StrykerReporter.instance.onBrowserComplete(null, { mutantCoverage, hitCount });378 StrykerReporter.instance.onRunComplete(null, runResults);379 }380});381function arrangeLauncherMock() {382 const karmaServerMock = sinon.createStubInstance(karma.Server);383 const launcherMock = sinon.createStubInstance(karma.launcher.Launcher);384 StrykerReporter.instance.karmaServer = karmaServerMock;385 karmaServerMock.get.returns(launcherMock);386 return { launcher: launcherMock, karmaServer: karmaServerMock };387}388function createKarmaSpec(overrides?: Partial<KarmaSpec>): KarmaSpec {389 return {390 description: 'baz',391 id: '1',392 log: [],393 skipped: false,394 success: true,395 suite: ['foo', 'bar'],396 time: 42,397 ...overrides,398 };399}400function createKarmaTestResults(overrides?: Partial<TestResults>): TestResults {401 return {402 disconnected: false,403 error: false,404 exitCode: 0,405 failed: 0,406 success: 0,407 ...overrides,408 };409}410function createBrowser(overrides?: Partial<Browser>): Browser {411 return {412 id: '123123',413 state: 'CONNECTED',414 ...overrides,415 };...
Using AI Code Generation
1var strykerParent = require('stryker-parent');2strykerParent.onGoingInit();3var strykerParent = require('stryker-parent');4strykerParent.onInit();5var strykerParent = require('stryker-parent');6strykerParent.onTestRun();7var strykerParent = require('stryker-parent');8strykerParent.onTestResult();9var strykerParent = require('stryker-parent');10strykerParent.onTestFrameworkStart();11var strykerParent = require('stryker-parent');12strykerParent.onAllTestResults();13var strykerParent = require('stryker-parent');14strykerParent.onInit();15var strykerParent = require('stryker-parent');16strykerParent.onTestRun();17var strykerParent = require('stryker-parent');18strykerParent.onTestResult();19var strykerParent = require('stryker-parent');20strykerParent.onTestFrameworkStart();21var strykerParent = require('stryker-parent');22strykerParent.onAllTestResults();23var strykerParent = require('stryker-parent');24strykerParent.onTestRun();25var strykerParent = require('stryker-parent');26strykerParent.onTestResult();27var strykerParent = require('stryker-parent');28strykerParent.onTestFrameworkStart();29var strykerParent = require('stryker-parent');
Using AI Code Generation
1var strykerParent = require('stryker-parent');2strykerParent.onGoingInit();3var strykerParent = require('stryker-parent');4strykerParent.onInitDone();5var strykerParent = require('stryker-parent');6strykerParent.onGoingInit();7var strykerParent = require('stryker-parent');8strykerParent.onInitDone();9var strykerParent = require('stryker-parent');10strykerParent.onGoingInit();11var strykerParent = require('stryker-parent');12strykerParent.onInitDone();13var strykerParent = require('stryker-parent');14strykerParent.onGoingInit();15var strykerParent = require('stryker-parent');16strykerParent.onInitDone();17var strykerParent = require('stryker-parent');18strykerParent.onGoingInit();19var strykerParent = require('stryker-parent');20strykerParent.onInitDone();21var strykerParent = require('stryker-parent');22strykerParent.onGoingInit();23var strykerParent = require('stryker-parent');24strykerParent.onInitDone();25var strykerParent = require('stryker-parent');26strykerParent.onGoingInit();27var strykerParent = require('stryker-parent');28strykerParent.onInitDone();
Using AI Code Generation
1const { onGoingInit } = require('stryker-parent');2const { Stryker } = require('stryker');3async function main() {4 await onGoingInit();5 const stryker = new Stryker();6 await stryker.runMutationTest();7}8main();9module.exports = function(config) {10 config.set({11 jest: {12 config: {13 },14 },15 });16};17module.exports = {18 testMatch: ['**/test/**/*.js?(x)', '**/?(*.)+(spec|test).js?(x)'],19 transform: {20 },21};22{23 "scripts": {24 },25 "devDependencies": {
Using AI Code Generation
1var strykerParent = require('stryker-parent');2var onGoingInit = strykerParent.onGoingInit;3var onGoingInitPromise = onGoingInit();4var strykerParent = require('stryker-parent');5var onGoingInit = strykerParent.onGoingInit;6var onGoingInitPromise = onGoingInit();7var strykerParent = require('stryker-parent');8var onGoingInit = strykerParent.onGoingInit;9var onGoingInitPromise = onGoingInit();10var strykerParent = require('stryker-parent');11var onGoingInit = strykerParent.onGoingInit;12var onGoingInitPromise = onGoingInit();13var strykerParent = require('stryker-parent');14var onGoingInit = strykerParent.onGoingInit;15var onGoingInitPromise = onGoingInit();16var strykerParent = require('stryker-parent');17var onGoingInit = strykerParent.onGoingInit;18var onGoingInitPromise = onGoingInit();19var strykerParent = require('stryker-parent');20var onGoingInit = strykerParent.onGoingInit;21var onGoingInitPromise = onGoingInit();22var strykerParent = require('stryker-parent');23var onGoingInit = strykerParent.onGoingInit;24var onGoingInitPromise = onGoingInit();25var strykerParent = require('stryker-parent');26var onGoingInit = strykerParent.onGoingInit;27var onGoingInitPromise = onGoingInit();28var strykerParent = require('stryker-parent');29var onGoingInit = strykerParent.onGoingInit;30var onGoingInitPromise = onGoingInit();31var strykerParent = require('stry
Using AI Code Generation
1const { onGoingInit } = require('stryker-parent');2onGoingInit("test");3const { onGoingInit } = require('stryker-parent');4onGoingInit("test");5const { onGoingInit } = require('stryker-parent');6onGoingInit("test");7const { onGoingInit } = require('stryker-parent');8onGoingInit("test");9const { onGoingInit } = require('stryker-parent');10onGoingInit("test");11const { onGoingInit } = require('stryker-parent');12onGoingInit("test");13const { onGoingInit } = require('stryker-parent');14onGoingInit("test");15const { onGoingInit } = require('stryker-parent');16onGoingInit("test");17const { onGoingInit } = require('stryker-parent');18onGoingInit("test");19const { onGoingInit } = require('stryker-parent');20onGoingInit("test");
Using AI Code Generation
1const stryker = require('stryker-parent');2const path = require('path');3const config = require('./stryker.conf.js');4const log = require('stryker-api').logging.getLogger('stryker');5 {pattern: 'test.js', included: true, mutated: false, included: true},6 {pattern: 'stryker.conf.js', included: true, mutated: false, included: true}7];8stryker.onGoingInit(config, files, {port: 9876, reporters: ['progress']});
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!!