Best JavaScript code snippet using stryker-parent
rpc.ts
Source:rpc.ts
...121 rpcApply.oneway = true;122 this.peer.send(rpcApply, undefined, serializationContext);123 return Promise.resolve();124 }125 return this.peer.createPendingResult((id, reject) => {126 rpcApply.id = id;127 this.peer.send(rpcApply, reject, serializationContext);128 })129 }130}131// todo: error constructor adds a "cause" variable in Chrome 93, Node v??132export class RPCResultError extends Error {133 constructor(peer: RpcPeer, message: string, public cause?: Error, options?: { name: string, stack: string | undefined }) {134 super(`${peer.selfName}:${peer.peerName}: ${message}`);135 if (options?.name) {136 this.name = options?.name;137 }138 if (options?.stack) {139 this.stack = `${peer.peerName}:${peer.selfName}\n${cause?.stack || options.stack}`;140 }141 }142}143function compileFunction(code: string, params?: ReadonlyArray<string>, options?: CompileFunctionOptions): any {144 params = params || [];145 const f = `(function(${params.join(',')}) {;${code};})`;146 return eval(f);147}148try {149 const fr = FinalizationRegistry;150}151catch (e) {152 (window as any).WeakRef = class WeakRef {153 target: any;154 constructor(target: any) {155 this.target = target;156 }157 deref(): any {158 return this.target;159 }160 };161 (window as any).FinalizationRegistry = class FinalizationRegistry {162 register() {163 }164 }165}166export interface RpcSerializer {167 serialize(value: any, serializationContext?: any): any;168 deserialize(serialized: any, serializationContext?: any): any;169}170interface LocalProxiedEntry {171 id: string;172 finalizerId: string | undefined;173}174export class RpcPeer {175 idCounter = 1;176 params: { [name: string]: any } = {};177 pendingResults: { [id: string]: Deferred } = {};178 proxyCounter = 1;179 localProxied = new Map<any, LocalProxiedEntry>();180 localProxyMap: { [id: string]: any } = {};181 remoteWeakProxies: { [id: string]: WeakRef<any> } = {};182 finalizers = new FinalizationRegistry(entry => this.finalize(entry as LocalProxiedEntry));183 nameDeserializerMap = new Map<string, RpcSerializer>();184 constructorSerializerMap = new Map<any, string>();185 transportSafeArgumentTypes = RpcPeer.getDefaultTransportSafeArgumentTypes();186 static readonly finalizerIdSymbol = Symbol('rpcFinalizerId');187 static getDefaultTransportSafeArgumentTypes() {188 const jsonSerializable = new Set<string>();189 jsonSerializable.add(Number.name);190 jsonSerializable.add(String.name);191 jsonSerializable.add(Object.name);192 jsonSerializable.add(Boolean.name);193 jsonSerializable.add(Array.name);194 return jsonSerializable;195 }196 static handleFunctionInvocations(thiz: PrimitiveProxyHandler<any>, target: any, p: PropertyKey, receiver: any): any {197 if (p === 'apply') {198 return (thisArg: any, args: any[]) => {199 return thiz.apply!(target, thiz, args);200 }201 }202 else if (p === 'call') {203 return (thisArg: any, ...args: any[]) => {204 return thiz.apply!(target, thiz, args);205 }206 }207 else if (p === 'toString' || p === Symbol.toPrimitive) {208 return (thisArg: any, ...args: any[]) => {209 return thiz.toPrimitive();210 }211 }212 }213 static readonly PROPERTY_PROXY_ONEWAY_METHODS = '__proxy_oneway_methods';214 static readonly PROPERTY_JSON_DISABLE_SERIALIZATION = '__json_disable_serialization';215 static readonly PROPERTY_PROXY_PROPERTIES = '__proxy_props';216 static readonly PROPERTY_JSON_COPY_SERIALIZE_CHILDREN = '__json_copy_serialize_children';217 static readonly PROBED_PROPERTIES = new Set<any>([218 'then',219 'constructor',220 '__proxy_id',221 '__proxy_constructor',222 '__proxy_peer',223 RpcPeer.PROPERTY_PROXY_ONEWAY_METHODS,224 RpcPeer.PROPERTY_JSON_DISABLE_SERIALIZATION,225 RpcPeer.PROPERTY_PROXY_PROPERTIES,226 RpcPeer.PROPERTY_JSON_COPY_SERIALIZE_CHILDREN,227 ]);228 constructor(public selfName: string, public peerName: string, public send: (message: RpcMessage, reject?: (e: Error) => void, serializationContext?: any) => void) {229 }230 createPendingResult(cb: (id: string, reject: (e: Error) => void) => void): Promise<any> {231 if (Object.isFrozen(this.pendingResults))232 return Promise.reject(new RPCResultError(this, 'RpcPeer has been killed'));233 const promise = new Promise((resolve, reject) => {234 const id = (this.idCounter++).toString();235 this.pendingResults[id] = { resolve, reject };236 cb(id, e => reject(new RPCResultError(this, e.message, e)));237 });238 // todo: make this an option so rpc doesn't nuke the process if uncaught?239 promise.catch(() => { });240 return promise;241 }242 kill(message?: string) {243 const error = new RPCResultError(this, message || 'peer was killed');244 for (const result of Object.values(this.pendingResults)) {245 result.reject(error);246 }247 this.pendingResults = Object.freeze({});248 this.remoteWeakProxies = Object.freeze({});249 this.localProxyMap = Object.freeze({});250 this.localProxied.clear();251 }252 // need a name/constructor map due to babel name mangling? fix somehow?253 addSerializer(ctr: any, name: string, serializer: RpcSerializer) {254 this.nameDeserializerMap.set(name, serializer);255 this.constructorSerializerMap.set(ctr, name);256 }257 finalize(entry: LocalProxiedEntry) {258 delete this.remoteWeakProxies[entry.id];259 const rpcFinalize: RpcFinalize = {260 __local_proxy_id: entry.id,261 __local_proxy_finalizer_id: entry.finalizerId,262 type: 'finalize',263 }264 this.send(rpcFinalize);265 }266 async getParam(param: string) {267 return this.createPendingResult((id, reject) => {268 const paramMessage: RpcParam = {269 id,270 type: 'param',271 param,272 };273 this.send(paramMessage, reject);274 });275 }276 evalLocal<T>(script: string, filename?: string, coercedParams?: { [name: string]: any }): T {277 const params = Object.assign({}, this.params, coercedParams);278 let compile: CompileFunction;279 try {280 // prevent bundlers from trying to include non-existent vm module.281 compile = module[`require`]('vm').compileFunction;...
ConnectionToCore.ts
Source:ConnectionToCore.ts
...230 protected async internalSendRequestAndWait(231 payload: Omit<ICoreRequestPayload, 'messageId' | 'sendDate'>,232 timeoutMs?: number,233 ): Promise<ICoreResponsePayload> {234 const { promise, id, resolve } = this.createPendingResult();235 const { command } = payload;236 if (command === 'Core.connect') this.connectRequestId = id;237 if (command === 'Core.disconnect') this.disconnectRequestId = id;238 let timeout: NodeJS.Timeout;239 if (timeoutMs) timeout = setTimeout(() => resolve(null), timeoutMs).unref();240 try {241 await this.internalSendRequest({242 messageId: id,243 sendDate: new Date(),244 ...payload,245 });246 } catch (error) {247 clearTimeout(timeout);248 if (error instanceof CanceledPromiseError) {249 this.pendingRequestsById.delete(id);250 return;251 }252 throw error;253 }254 // now run to completion with timeout255 try {256 return await promise;257 } finally {258 clearTimeout(timeout);259 }260 }261 protected onEvent(payload: ICoreEventPayload): void {262 const { meta, listenerId, eventArgs } = payload as ICoreEventPayload;263 const session = this.getSession(meta.sessionId);264 session?.onEvent(meta, listenerId, eventArgs);265 }266 protected async onConnectionTerminated(): Promise<void> {267 if (this.isConnectionTerminated) return;268 this.isConnectionTerminated = true;269 await this.internalDisconnect();270 if (this.connectRequestId) {271 this.onResponse(this.connectRequestId, {272 data: this.didAutoConnect ? new DisconnectedFromCoreError(this.resolvedHost) : null,273 });274 }275 if (this.disconnectRequestId) {276 this.onResponse(this.disconnectRequestId, {277 data: null,278 });279 }280 }281 protected onResponse(id: string, message: ICoreResponsePayload): void {282 const pending = this.pendingRequestsById.get(id);283 if (!pending) return;284 this.pendingRequestsById.delete(id);285 const isInternalRequest = this.connectRequestId === id || this.disconnectRequestId === id;286 if (this.disconnectRequestId === id) this.disconnectRequestId = null;287 if (this.connectRequestId === id) this.connectRequestId = null;288 if (message.data instanceof Error) {289 let responseError = message.data;290 const isDisconnected =291 this.isDisconnecting ||292 responseError.name === SessionClosedOrMissingError.name ||293 (responseError as any).isDisconnecting === true;294 delete (responseError as any).isDisconnecting;295 if (!isInternalRequest && isDisconnected) {296 responseError = new DisconnectedFromCoreError(this.resolvedHost);297 }298 this.rejectPendingRequest(pending, responseError);299 } else {300 pending.resolve({ data: message.data });301 }302 }303 protected cancelPendingRequests(): void {304 const host = String(this.resolvedHost);305 for (const entry of this.pendingRequestsById.values()) {306 const id = entry.id;307 if (this.connectRequestId === id || this.disconnectRequestId === id) {308 continue;309 }310 this.pendingRequestsById.delete(id);311 this.rejectPendingRequest(entry, new DisconnectedFromCoreError(host));312 }313 this.commandQueue.stop(new DisconnectedFromCoreError(host));314 this.coreSessions.stop(new DisconnectedFromCoreError(host));315 }316 private createPendingResult(): IResolvablePromiseWithId {317 const resolvablePromise = createPromise<ICoreResponsePayload>() as IResolvablePromiseWithId;318 this.lastId += 1;319 const id = this.lastId.toString();320 resolvablePromise.id = id;321 this.pendingRequestsById.set(id, resolvablePromise);322 return this.pendingRequestsById.get(id);323 }324 private rejectPendingRequest(pending: IResolvablePromiseWithId, error: Error): void {325 error.stack += `\n${'------CONNECTION'.padEnd(50, '-')}\n${pending.stack}`;326 pending.reject(error);327 }328}329interface IResolvablePromiseWithId extends IResolvablePromise<ICoreResponsePayload> {330 id: string;...
producers.ts
Source:producers.ts
1import type { TestResult, AggregatedResult, AssertionResult, SerializableError } from '@jest/test-result';2import type { EnvironmentContext } from '@jest/environment';3import { Circus, Config } from '@jest/types';4import { factory } from '@stryker-mutator/test-helpers';5import { JestOptions } from '../../src-generated/jest-runner-options';6import { JestRunResult } from '../../src/jest-run-result';7import { JestRunnerOptionsWithStrykerOptions } from '../../src/jest-runner-options-with-stryker-options';8export const createJestRunnerOptionsWithStrykerOptions = (overrides?: Partial<JestOptions>): JestRunnerOptionsWithStrykerOptions => {9 return factory.strykerWithPluginOptions({ jest: createJestOptions(overrides) });10};11export const createJestOptions = (overrides?: Partial<JestOptions>): JestOptions => {12 return {13 enableFindRelatedTests: true,14 projectType: 'custom',15 ...overrides,16 };17};18export function createAssertionResult(overrides?: Partial<AssertionResult>): AssertionResult {19 return {20 ancestorTitles: [],21 failureMessages: [],22 fullName: 'foo should be bar',23 numPassingAsserts: 1,24 status: 'passed',25 title: 'should be bar',26 duration: 25,27 failureDetails: [],28 ...overrides,29 };30}31export function createJestRunResult(overrides?: Partial<JestRunResult>): JestRunResult {32 return {33 globalConfig: createGlobalConfig(),34 results: createJestAggregatedResult(),35 ...overrides,36 };37}38export function createJestAggregatedResult(overrides?: Partial<AggregatedResult>): AggregatedResult {39 return {40 numFailedTestSuites: 0,41 numFailedTests: 0,42 numPassedTestSuites: 0,43 numPassedTests: 0,44 numPendingTestSuites: 0,45 numPendingTests: 0,46 numRuntimeErrorTestSuites: 0,47 numTodoTests: 0,48 numTotalTestSuites: 0,49 numTotalTests: 0,50 openHandles: [],51 snapshot: {52 added: 0,53 didUpdate: false,54 failure: false,55 filesAdded: 0,56 filesRemoved: 0,57 filesRemovedList: [],58 filesUnmatched: 0,59 filesUpdated: 0,60 matched: 0,61 total: 0,62 unchecked: 0,63 uncheckedKeysByFile: [],64 unmatched: 0,65 updated: 0,66 },67 startTime: 0,68 success: true,69 testResults: [],70 wasInterrupted: false,71 ...overrides,72 };73}74export function createJestTestResult(overrides?: Partial<TestResult>): TestResult {75 return {76 leaks: false,77 numFailingTests: 0,78 numPassingTests: 0,79 numPendingTests: 0,80 numTodoTests: 0,81 openHandles: [],82 perfStats: {83 runtime: 0,84 slow: false,85 end: 0,86 start: 0,87 },88 skipped: false,89 snapshot: {90 added: 0,91 fileDeleted: false,92 matched: 0,93 unchecked: 0,94 uncheckedKeys: [],95 unmatched: 0,96 updated: 0,97 },98 testFilePath: '',99 testResults: [],100 ...overrides,101 } as TestResult; // Do this cast to prevent breaking builds when unused options are added102}103export function createSerializableError(overrides?: Partial<SerializableError>): SerializableError {104 return {105 message: 'message',106 stack: 'stack',107 code: 'TEST',108 type: 'FooError',109 ...overrides,110 };111}112export const createFailResult = (): AggregatedResult =>113 createJestAggregatedResult({114 success: false,115 testResults: [116 createJestTestResult({117 testFilePath: 'qux.js',118 testResults: [119 createAssertionResult({120 failureMessages: ['Fail message 1', 'Fail message 2'],121 fullName: 'App render renders without crashing',122 duration: 2,123 status: 'failed',124 }),125 createAssertionResult({126 duration: 0,127 failureMessages: ['Fail message 3', 'Fail message 4'],128 fullName: 'App render renders without crashing',129 status: 'failed',130 }),131 ],132 }),133 createJestTestResult({134 testFilePath: 'quux.js',135 testResults: [136 createAssertionResult({137 ancestorTitles: ['App'],138 duration: 23,139 location: { line: 42, column: 43 },140 failureMessages: [],141 fullName: 'App renders without crashing',142 numPassingAsserts: 0,143 status: 'passed',144 title: 'renders without crashing',145 }),146 ],147 }),148 ],149 });150export const createGlobalConfig = (): Config.GlobalConfig =>151 ({152 bail: 1,153 changedFilesWithAncestor: true,154 collectCoverage: false,155 } as Config.GlobalConfig); // Do this cast to prevent breaking builds when unused options are added156export const createEnvironmentContext = (overrides?: Partial<EnvironmentContext>): EnvironmentContext =>157 ({158 testPath: 'foo.js',159 ...overrides,160 } as EnvironmentContext); // Do this cast to prevent breaking builds when unused options are added161export const createProjectConfig = (): Config.ProjectConfig =>162 ({163 detectLeaks: true,164 } as Config.ProjectConfig); // Do this cast to prevent breaking builds when unused options are added165export const createCircusDescribeBlock = (overrides?: Partial<Circus.DescribeBlock>): Circus.DescribeBlock =>166 ({167 name: 'ROOT_SUITE',168 ...overrides,169 } as Circus.DescribeBlock); // Do this cast to prevent breaking builds when unused options are added170export const createCircusTestEntry = (overrides?: Partial<Circus.TestEntry>): Circus.TestEntry =>171 ({172 name: 'should be bar',173 parent: createCircusDescribeBlock({ name: 'foo', parent: createCircusDescribeBlock() }),174 ...overrides,175 } as Circus.TestEntry); // Do this casts to prevent breaking builds when unused options are added176export const createCircusTestStartEvent = (test = createCircusTestEntry()): Circus.Event => ({177 name: 'test_start',178 test,179});180export const createCircusRunStartEvent = (): Circus.AsyncEvent => ({181 name: 'run_start',182});183export const createCircusState = (): Circus.State =>184 ({185 hasFocusedTests: false,186 } as Circus.State); // Do this casts to prevent breaking builds when unused options are added187export const createSuccessResult = (): AggregatedResult =>188 createJestAggregatedResult({189 success: true,190 testResults: [191 createJestTestResult({192 testFilePath: 'foo.js',193 testResults: [194 createAssertionResult({195 fullName: 'App renders without crashing',196 status: 'passed',197 location: { column: 4, line: 3 },198 duration: 23,199 }),200 ],201 }),202 ],203 wasInterrupted: false,204 });205export const createPendingResult = (): AggregatedResult =>206 createJestAggregatedResult({207 success: true,208 testResults: [209 createJestTestResult({210 testFilePath: 'bar.js',211 testResults: [212 createAssertionResult({213 duration: 0,214 fullName: 'App renders without crashing',215 status: 'pending',216 }),217 ],218 }),219 ],220 });221export const createTodoResult = (): AggregatedResult =>222 createJestAggregatedResult({223 success: true,224 testResults: [225 createJestTestResult({226 skipped: false,227 testFilePath: 'baz.js',228 testResults: [229 createAssertionResult({230 duration: 4,231 fullName: 'App renders without crashing',232 status: 'passed',233 }),234 createAssertionResult({235 duration: 0,236 fullName: 'App renders without crashing with children',237 status: 'todo',238 }),239 ],240 }),241 ],...
Using AI Code Generation
1module.exports = {2 createPendingResult: (testFile, testMethod) => {3 }4};5const parent = require('stryker-parent');6module.exports = {7 createPendingResult: (testFile, testMethod) => {8 parent.createPendingResult(testFile, testMethod);9 }10};11const child = require('stryker-child');12child.createPendingResult('test.js', 'testMethod');13const child = require('stryker-child');14child.createPendingResult('test.js', 'testMethod');15const parent = require('stryker-parent');16module.exports = {17 createPendingResult: (testFile, testMethod) => {18 parent.createPendingResult(testFile, testMethod);19 }20};21module.exports = {22 createPendingResult: (testFile, testMethod) => {23 }24};
Using AI Code Generation
1var strykerParent = require('stryker-parent');2var stryker = new strykerParent.Stryker();3var result = stryker.createPendingResult();4console.log(result);5var strykerParent = require('stryker-parent');6var stryker = new strykerParent.Stryker();7var result = stryker.createPendingResult();8console.log(result);9var strykerParent = require('stryker-parent');10var stryker = new strykerParent.Stryker();11var result = stryker.createPendingResult();12console.log(result);13var strykerParent = require('stryker-parent');14var stryker = new strykerParent.Stryker();15var result = stryker.createPendingResult();16console.log(result);17var strykerParent = require('stryker-parent');18var stryker = new strykerParent.Stryker();19var result = stryker.createPendingResult();20console.log(result);21var strykerParent = require('stryker-parent');22var stryker = new strykerParent.Stryker();23var result = stryker.createPendingResult();24console.log(result);25var strykerParent = require('stryker-parent');26var stryker = new strykerParent.Stryker();27var result = stryker.createPendingResult();28console.log(result);29var strykerParent = require('stryker-parent');30var stryker = new strykerParent.Stryker();31var result = stryker.createPendingResult();32console.log(result);33var strykerParent = require('stryker-parent');
Using AI Code Generation
1const { createPendingResult } = require('stryker-parent');2module.exports = function () {3 return createPendingResult('test', 'test');4}5module.exports = function (config) {6 config.set({7 customTestRunner: {8 options: {9 }10 }11 });12};
Using AI Code Generation
1var pendingResult = createPendingResult('test');2completePendingResult(pendingResult, 'test');3completePendingResult(pendingResult, 'test');4function createPendingResult(name) {5 return {name: name};6}7function completePendingResult(pendingResult, name) {8 pendingResult[name] = true;9 if (pendingResult.test && pendingResult.test2) {10 }11}
Using AI Code Generation
1var stryker = require('stryker-parent');2var test = stryker.createPendingResult('test name');3test.done();4test.done();5var stryker = require('stryker-parent');6var test = stryker.createPendingResult('test name');7test.done();8test.done();9{ id: 'test name', name: 'test name', status: 'pending' }10{ id: 'test name', name: 'test name', status: 'pending' }11var stryker = require('stryker-parent');12var test = stryker.createPendingResult('test name');13test.done();14test = test.done();15var stryker = require('stryker-parent');16var test = stryker.createPendingResult('test name');17test.done();18test = test.done();
Using AI Code Generation
1const { createPendingResult } = require('stryker-parent');2const { some, async } = require('test');3describe('a suite', () => {4 it('should fail', () => {5 return createPendingResult('some reason');6 });7});8module.exports = function(config) {9 config.set({10 jest: {11 config: require('./jest.config.js'),
Using AI Code Generation
1import { createPendingResult } from 'stryker-parent';2import { assert } from 'chai';3describe('Test', () => {4 it('should pass', () => {5 const result = createPendingResult();6 assert.isTrue(result);7 });8});9module.exports = function(config) {10 config.set({11 });12};13{14 "dependencies": {15 }16}17module.exports = {18 createPendingResult: function() {19 return true;20 }21};
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!!