How to use spawnNewWorker method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

BasicPool.spec.ts

Source:BasicPool.spec.ts Github

copy

Full Screen

...7 const workerFileUrl = new URL('file:///worker.cjs');8 const workerId = 0;9 const pool = new BasicPool(workerFileUrl, workerId);10 // Act11 pool.spawnNewWorker();12 // Assert13 expect(Worker).toHaveBeenCalledTimes(1);14 expect(Worker).toHaveBeenCalledWith(workerFileUrl, { workerData: { currentWorkerId: workerId } });15 expect(on).toHaveBeenCalled();16 expect(postMessage).not.toHaveBeenCalled();17 });18 describe('ready worker', () => {19 it('should spawn workers marked as available and not faulty', async () => {20 // Arrange21 const { on } = mockWorker();22 const workerFileUrl = new URL('file:///worker.cjs');23 const workerId = 0;24 const pool = new BasicPool(workerFileUrl, workerId);25 // Act26 const workerPromise = pool.spawnNewWorker();27 fireOnlineEvent(on);28 const worker = await workerPromise;29 // Assert30 expect(worker.isAvailable()).toBe(true);31 expect(worker.isFaulty()).toBe(false);32 });33 it('should mark the worker as not available but not faulty while waiting answers', async () => {34 // Arrange35 const { on, postMessage } = mockWorker();36 const workerFileUrl = new URL('file:///worker.cjs');37 const workerId = 0;38 const onSuccess = jest.fn();39 const onFailure = jest.fn();40 const pool = new BasicPool<string, string>(workerFileUrl, workerId);41 const workerPromise = pool.spawnNewWorker();42 fireOnlineEvent(on);43 const worker = await workerPromise;44 // Act45 worker.register('to-worker', onSuccess, onFailure);46 // Assert47 expect(worker.isAvailable()).toBe(false);48 expect(worker.isFaulty()).toBe(false);49 expect(postMessage).toHaveBeenCalledTimes(1);50 expect(onSuccess).not.toHaveBeenCalled();51 expect(onFailure).not.toHaveBeenCalled();52 });53 it('should call success handler and release the worker as soon as receiving a successful answer', async () => {54 // Arrange55 const { on, postMessage } = mockWorker();56 const workerFileUrl = new URL('file:///worker.cjs');57 const workerId = 0;58 const onSuccess = jest.fn();59 const onFailure = jest.fn();60 const successMessage = 'success!';61 const pool = new BasicPool<string, string>(workerFileUrl, workerId);62 const workerPromise = pool.spawnNewWorker();63 fireOnlineEvent(on);64 const worker = await workerPromise;65 worker.register('to-worker', onSuccess, onFailure);66 // Act67 const receivedMessage: PoolToWorkerMessage<string> = postMessage.mock.calls[0][0];68 const receivedRunId = receivedMessage.runId;69 const message: WorkerToPoolMessage<string> = { runId: receivedRunId, success: true, output: successMessage };70 const onMessageHandler = on.mock.calls.find(([eventName]) => eventName === 'message')![1];71 onMessageHandler(message); // emulate success72 // Assert73 expect(onSuccess).toHaveBeenCalledTimes(1);74 expect(onSuccess).toHaveBeenCalledWith(successMessage);75 expect(worker.isAvailable()).toBe(true);76 expect(worker.isFaulty()).toBe(false);77 expect(postMessage).toHaveBeenCalledTimes(1);78 expect(onFailure).not.toHaveBeenCalled();79 });80 it('should call failure handler and release the worker as soon as receiving a failed answer', async () => {81 // Arrange82 const { on, postMessage } = mockWorker();83 const workerFileUrl = new URL('file:///worker.cjs');84 const workerId = 0;85 const onSuccess = jest.fn();86 const onFailure = jest.fn();87 const errorMessage = 'oups there was an error!';88 const pool = new BasicPool<string, string>(workerFileUrl, workerId);89 const workerPromise = pool.spawnNewWorker();90 fireOnlineEvent(on);91 const worker = await workerPromise;92 worker.register('to-worker', onSuccess, onFailure);93 // Act94 const receivedMessage: PoolToWorkerMessage<string> = postMessage.mock.calls[0][0];95 const receivedRunId = receivedMessage.runId;96 const message: WorkerToPoolMessage<string> = { runId: receivedRunId, success: false, error: errorMessage };97 const onMessageHandler = on.mock.calls.find(([eventName]) => eventName === 'message')![1];98 onMessageHandler(message); // emulate failure99 // Assert100 expect(onFailure).toHaveBeenCalledTimes(1);101 expect(onFailure).toHaveBeenCalledWith(errorMessage);102 expect(worker.isAvailable()).toBe(true);103 expect(worker.isFaulty()).toBe(false);104 expect(postMessage).toHaveBeenCalledTimes(1);105 expect(onSuccess).not.toHaveBeenCalled();106 });107 it('should ignore success or failures not related to the current run', async () => {108 // Arrange109 const { on, postMessage } = mockWorker();110 const workerFileUrl = new URL('file:///worker.cjs');111 const workerId = 0;112 const onSuccess = jest.fn();113 const onFailure = jest.fn();114 const pool = new BasicPool<string, string>(workerFileUrl, workerId);115 const workerPromise = pool.spawnNewWorker();116 fireOnlineEvent(on);117 const worker = await workerPromise;118 worker.register('to-worker', onSuccess, onFailure);119 // Act120 const receivedMessage: PoolToWorkerMessage<string> = postMessage.mock.calls[0][0];121 const receivedRunId = receivedMessage.runId;122 const message1: WorkerToPoolMessage<string> = { runId: receivedRunId - 1, success: true, output: 'm1' };123 const message2: WorkerToPoolMessage<string> = { runId: receivedRunId + 1, success: true, output: 'm2' };124 const message3: WorkerToPoolMessage<string> = { runId: receivedRunId + 1, success: false, error: 'm3' };125 const onMessageHandler = on.mock.calls.find(([eventName]) => eventName === 'message')![1];126 onMessageHandler(message1);127 onMessageHandler(message2);128 onMessageHandler(message3);129 // Assert130 expect(worker.isAvailable()).toBe(false); // still waiting messages for 'receivedRunId'131 expect(worker.isFaulty()).toBe(false);132 expect(postMessage).toHaveBeenCalledTimes(1);133 expect(onSuccess).not.toHaveBeenCalled();134 expect(onFailure).not.toHaveBeenCalled();135 });136 it('should call failure handler and mark the worker as faulty when receiving messageerror message', async () => {137 // Arrange138 const { on, postMessage } = mockWorker();139 const workerFileUrl = new URL('file:///worker.cjs');140 const workerId = 0;141 const onSuccess = jest.fn();142 const onFailure = jest.fn();143 const pool = new BasicPool<string, string>(workerFileUrl, workerId);144 const workerPromise = pool.spawnNewWorker();145 fireOnlineEvent(on);146 const worker = await workerPromise;147 worker.register('to-worker', onSuccess, onFailure);148 // Act149 const onErrorHandler = on.mock.calls.find(([eventName]) => eventName === 'messageerror')![1];150 onErrorHandler(new Error('failed to serialize/deserialize payload!')); // emulate messageerror message151 // Assert152 expect(onFailure).toHaveBeenCalledTimes(1);153 expect(worker.isAvailable()).toBe(true); // we can recover immediately from such problems154 expect(worker.isFaulty()).toBe(false);155 expect(postMessage).toHaveBeenCalledTimes(1);156 expect(onSuccess).not.toHaveBeenCalled();157 });158 it('should call failure handler and mark the worker as faulty when receiving error message', async () => {159 // Arrange160 const { on, postMessage } = mockWorker();161 const workerFileUrl = new URL('file:///worker.cjs');162 const workerId = 0;163 const onSuccess = jest.fn();164 const onFailure = jest.fn();165 const pool = new BasicPool<string, string>(workerFileUrl, workerId);166 const workerPromise = pool.spawnNewWorker();167 fireOnlineEvent(on);168 const worker = await workerPromise;169 worker.register('to-worker', onSuccess, onFailure);170 // Act171 const onErrorHandler = on.mock.calls.find(([eventName]) => eventName === 'error')![1];172 onErrorHandler(new Error('boom!')); // emulate error message173 // Assert174 expect(onFailure).toHaveBeenCalledTimes(1);175 expect(worker.isAvailable()).toBe(false); // we don't want to recover such worker176 expect(worker.isFaulty()).toBe(true);177 expect(postMessage).toHaveBeenCalledTimes(1);178 expect(onSuccess).not.toHaveBeenCalled();179 });180 it('should call failure handler and mark the worker as faulty when receiving exit message', async () => {181 // Arrange182 const { on, postMessage } = mockWorker();183 const workerFileUrl = new URL('file:///worker.cjs');184 const workerId = 0;185 const onSuccess = jest.fn();186 const onFailure = jest.fn();187 const pool = new BasicPool<string, string>(workerFileUrl, workerId);188 const workerPromise = pool.spawnNewWorker();189 fireOnlineEvent(on);190 const worker = await workerPromise;191 worker.register('to-worker', onSuccess, onFailure);192 // Act193 const exitCode = 101;194 const onExitHandler = on.mock.calls.find(([eventName]) => eventName === 'exit')![1];195 onExitHandler(exitCode); // emulate exit message196 // Assert197 expect(onFailure).toHaveBeenCalledTimes(1);198 expect(worker.isAvailable()).toBe(false); // we don't want to recover such worker199 expect(worker.isFaulty()).toBe(true);200 expect(postMessage).toHaveBeenCalledTimes(1);201 expect(onSuccess).not.toHaveBeenCalled();202 });203 });204 describe('faulty worker', () => {205 it('should throw when spawning worker if messageerror received before online', async () => {206 // Arrange207 const { on } = mockWorker();208 const workerFileUrl = new URL('file:///worker.cjs');209 const workerId = 0;210 const pool = new BasicPool<string, string>(workerFileUrl, workerId);211 const workerPromise = pool.spawnNewWorker();212 // Act213 const onExitHandler = on.mock.calls.find(([eventName]) => eventName === 'messageerror')![1];214 onExitHandler(new Error('Failure in serialization or deserialization')); // emulate messageerror message215 // Assert216 await expect(workerPromise).rejects.toThrowError();217 });218 it('should throw when spawning worker if error received before online', async () => {219 // Arrange220 const { on } = mockWorker();221 const workerFileUrl = new URL('file:///worker.cjs');222 const workerId = 0;223 const pool = new BasicPool<string, string>(workerFileUrl, workerId);224 const workerPromise = pool.spawnNewWorker();225 // Act226 const onExitHandler = on.mock.calls.find(([eventName]) => eventName === 'error')![1];227 onExitHandler(new Error('An error')); // emulate error message228 // Assert229 await expect(workerPromise).rejects.toThrowError();230 });231 it('should throw when spawning worker if exit received before online', async () => {232 // Arrange233 const { on } = mockWorker();234 const workerFileUrl = new URL('file:///worker.cjs');235 const workerId = 0;236 const pool = new BasicPool<string, string>(workerFileUrl, workerId);237 const workerPromise = pool.spawnNewWorker();238 // Act239 const exitCode = 101;240 const onExitHandler = on.mock.calls.find(([eventName]) => eventName === 'exit')![1];241 onExitHandler(exitCode); // emulate exit message242 // Assert243 await expect(workerPromise).rejects.toThrowError();244 });245 });246});247// Helpers248function mockWorker() {249 const Worker = jest.spyOn(WorkerThreadsMock, 'Worker');250 const on = jest.fn();251 const postMessage = jest.fn();...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...21 if (!process.env.NODE_ENV || process.env.NODE_ENV.toLowerCase() !== 'production') {22 Logger.warning('Node.js is not running in production mode. Consider running in production mode: export NODE_ENV=production')23 }24 Logger.log('Starting traaittCASH Blockchain Relay Agent...')25 spawnNewWorker()26 cluster.on('exit', (worker, code, signal) => {27 Logger.error('Worker %s died', worker.process.pid)28 spawnNewWorker()29 })30} else if (cluster.isWorker) {31 const rabbit = new RabbitMQ(32 process.env.RABBIT_PUBLIC_SERVER || 'localhost',33 process.env.RABBIT_PUBLIC_USERNAME || '',34 process.env.RABBIT_PUBLIC_PASSWORD || '',35 false36 )37 rabbit.on('log', log => {38 Logger.log('[RABBIT] %s', log)39 })40 rabbit.on('connect', () => {41 Logger.log('[RABBIT] connected to server at %s', process.env.RABBIT_PUBLIC_SERVER || 'localhost')42 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { spawnNewWorker } = require('fast-check-monorepo');2const path = require('path');3const workerPath = path.join(__dirname, 'worker.js');4const worker = spawnNewWorker(workerPath);5worker.on('message', (msg) => {6 console.log('Message from worker', msg);7});8worker.on('exit', (code) => {9 console.log(`Worker stopped with exit code ${code}`);10});11worker.postMessage({ hello: 'world' });12const { parentPort, workerData } = require('worker_threads');13parentPort.postMessage({ worker: workerData });14parentPort.on('message', (msg) => {15 console.log('Message from parent:', msg);16});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { spawnNewWorker } = require('fast-check-monorepo/lib/WorkerProcess.js');2const worker = spawnNewWorker();3worker.on('message', (data) => {4 console.log('message received', data);5});6worker.on('error', (error) => {7 console.log('error received', error);8});9worker.on('exit', (code) => {10 console.log('worker exited with code', code);11});12worker.postMessage('Hello world');13const { spawnNewWorker } = require('fast-check/lib/WorkerProcess');14const worker = spawnNewWorker();15worker.on('message', (data) => {16 console.log('message received', data);17});18worker.on('error', (error) => {19 console.log('error received', error);20});21worker.on('exit', (code) => {22 console.log('worker exited with code', code);23});24worker.postMessage('Hello world');25 at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)26 at Function.Module._load (internal/modules/cjs/loader.js:725:27)27 at Module.require (internal/modules/cjs/loader.js:952:19)28 at require (internal/modules/cjs/helpers.js:88:18)29 at Object.<anonymous> (/Users/abc/xyz/test2.js:2:25)30 at Module._compile (internal/modules/cjs/loader.js:1063:30)31 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)32 at Module.load (internal/modules/cjs/loader.js:928:32)33 at Function.Module._load (internal/modules/cjs/loader.js:769:14)34 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const { spawnNewWorker } = require("fast-check/lib/runner/worker/SpawnNewWorker");3const arb = fc.array(fc.integer());4spawnNewWorker(arb, 100).then((res) => {5 console.log(res);6});7 at generate (C:\Users\user\Documents\test\node_modules\fast-check\lib\arbitrary\array.js:31:29)8 at generate (C:\Users\user\Documents\test\node_modules\fast-check\lib\arbitrary\generic\GeneratorArbitrary.js:26:29)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { spawnNewWorker } = require('fast-check');2const arb = fc.integer(1, 100);3const worker = spawnNewWorker();4arb.generate(worker).then((v) => console.log(`Value: ${v}`));5 throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);6Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/abc/Desktop/abc/node_modules/fast-check/lib/runner/WorkerRunner.js7 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1174:13)8 at Module.load (internal/modules/cjs/loader.js:1002:32)9 at Function.Module._load (internal/modules/cjs/loader.js:901:14)10 at Module.require (internal/modules/cjs/loader.js:1044:19)11 at require (internal/modules/cjs/helpers.js:77:18)12 at Object.<anonymous> (/home/abc/Desktop/abc/node_modules/fast-check/lib/runner/WorkerRunnerFactory.js:1:110)13 at Module._compile (internal/modules/cjs/loader.js:1137:30)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { spawnNewWorker } = require('fast-check-monorepo');2const options = {3};4const worker = spawnNewWorker(options);5worker.on('message', (msg) => {6 console.log(msg);7});8worker.on('exit', (code) => {9 console.log(`child process exited with code ${code}`);10});11const { parentPort } = require('worker_threads');12parentPort.postMessage('hello');13const { spawnNewWorker } = require('fast-check-monorepo');14const options = {15};16const worker = spawnNewWorker(options);17worker.on('message', (msg) => {18 console.log(msg);19});20worker.on('exit', (code) => {21 console.log(`child process exited with code ${code}`);22});23const { parentPort } = require('worker_threads');24parentPort.postMessage('hello');25const { spawnNewWorker } = require('fast-check-monorepo');26const options = {27};28const worker = spawnNewWorker(options);29worker.on('message', (msg) => {30 console.log(msg);31});32worker.on('exit', (code) => {33 console.log(`child process exited with code ${code}`);34});35const { parentPort } = require('worker_threads');36parentPort.postMessage('hello');37const { spawnNewWorker } = require('fast-check-monorepo');38const options = {39};40const worker = spawnNewWorker(options);41worker.on('message', (msg) => {42 console.log(msg);43});44worker.on('exit', (code) => {45 console.log(`child process exited with code ${code}`);46});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fast-check-monorepo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful