Best JavaScript code snippet using fast-check-monorepo
BasicPool.spec.ts
Source:BasicPool.spec.ts
1import { BasicPool, PoolToWorkerMessage, WorkerToPoolMessage } from '../../../src/internals/worker-pool/BasicPool.js';2import * as WorkerThreadsMock from 'node:worker_threads';3describe('BasicPool', () => {4 it('should instantly register handlers when spawning workers', () => {5 // Arrange6 const { Worker, on, postMessage } = mockWorker();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();252 Worker.mockImplementation(253 () =>254 ({255 on,256 postMessage,257 } as unknown as WorkerThreadsMock.Worker)258 );259 return { Worker, on, postMessage };260}261function fireOnlineEvent(on: jest.Mock<any, any>) {262 const onOnlineHandler = on.mock.calls.find(([eventName]) => eventName === 'online')![1];263 onOnlineHandler();...
worker.js
Source:worker.js
1/**2 * Namespacing3 */4(function(_c){5 /** 6 * Makes sure the messages are always nicely formatted according to my expectations.7 * Meaing: always define an action and params8 */9 var message = function(action, parameters){10 comparativus.worker.thread.postMessage({'action' : action, 'params' : parameters});11 };12 /**13 * Contains the messaging interface with the workers14 */15 _c.worker = {16 /**17 * Reference to the single thread we're working with18 */19 thread: undefined,20 /**21 * Does all the necessary thread initialization. Creates the new 22 * Webworker and assigns a message handler.23 */24 init: function(){25 //create a new thread (force refresh in debug)26 var workerFileURL = 'js/thread.js';27 if(comparativus.util.isDebug()) workerFileURL += "?v=" + (new Date()).getTime();28 29 //Finally create a worker from the created url30 comparativus.worker.thread = new Worker(workerFileURL);31 32 //And assign the correct handler function for workers33 comparativus.worker.thread.onmessage = comparativus.worker.onmessage;34 },35 /**36 * Messages the worker to prepare the text for usage37 * This function loads data files from disk. Just used for 38 * testing purposes. Don't clean the file again if it is already loaded39 */40 prepareText: function(id){41 var config = {42 'stripWhiteSpace': $('#stripWhiteSpace').val(),43 'stripPunctuation': $('#stripPunctuation').val()44 };45 message('prepareText', {'id': id, 'text': comparativus.text.getByID(id).plain, 'config': config}); 46 },47 /**48 * Messages the worker to start building the dictionary.49 * Builds the dictionary for the text that is registered under50 * the provided name51 */52 buildDictionary: function(id){53 message('buildDictionary', {'id':id , text: comparativus.text.getByID(id).clean});54 },55 /**56 * What happens when the main thread recieves a message from the worker. This is all defined 57 * in this function58 */59 onmessage: function(event){60 //it is assumed that any communication from a worker assigns these values61 var action = event.data.action;62 var params = event.data.params;63 64 //Switch based on the action parameter65 switch(action){66 case 'DictDone':67 comparativus.dicts.toBuild --;68 comparativus.dicts[params.id] = params.dictionary;69 if(comparativus.dicts.toBuild == 0){70 comparativus.startComparison();71 }72 break;73 case 'PrepareDone':74 comparativus.text.setByID(params.id, params.text);75 $('#info' + params.id).html('Length: ' + params.text.length + ' characters');76 comparativus.worker.buildDictionary(params.id);77 break;78 }79 }80 };81 ...
main.properties.cjs
Source:main.properties.cjs
1const { pathToFileURL } = require('node:url');2const fc = require('fast-check');3const { workerProperty } = require('@fast-check/worker');4const workerFileUrl = pathToFileURL(__filename);5exports.blockEventLoopProperty = workerProperty(6 workerFileUrl,7 fc.integer({ min: -1000, max: 1000 }),8 fc.integer({ min: -1000, max: 1000 }),9 (from, to) => {10 for (let i = from; i !== to; ++i) {11 // Loop from "from" to "to" possibly NEVER ending12 }13 }14);15exports.passingProperty = workerProperty(16 workerFileUrl,17 fc.integer({ min: -1000, max: 1000 }),18 fc.integer({ min: -1000, max: 1000 }),19 (from, to) => {20 for (let i = from; i <= to; ++i) {21 // Loop from "from" to "to" ALWAYS finite22 }23 }24);25exports.failingProperty = workerProperty(26 workerFileUrl,27 fc.integer({ min: -1000, max: 1000 }),28 fc.integer({ min: -1000, max: 1000 }),29 (_from, _to) => {30 throw new Error("I'm a failing property");31 }32);33exports.buildUnregisteredProperty = () =>34 workerProperty(35 workerFileUrl,36 fc.integer({ min: -1000, max: 1000 }),37 fc.integer({ min: -1000, max: 1000 }),38 (_from, _to) => {39 return true; // success40 }...
Using AI Code Generation
1const workerFileUrl = require('fast-check-monorepo').workerFileUrl;2const workerFileUrl = require('fast-check').workerFileUrl;3const { workerFileUrl } = require('fast-check-monorepo');4const { workerFileUrl } = require('fast-check');5import { workerFileUrl } from 'fast-check-monorepo';6import { workerFileUrl } from 'fast-check';7import workerFileUrl from 'fast-check-monorepo/lib/workerFileUrl';8import workerFileUrl from 'fast-check/lib/workerFileUrl';9import workerFileUrl from 'fast-check-monorepo/dist/lib/workerFileUrl';10import workerFileUrl from 'fast-check/dist/lib/workerFileUrl';11import workerFileUrl from 'fast-check-monorepo/dist/lib/workerFileUrl.js';12import workerFileUrl from 'fast-check/dist/lib/workerFileUrl.js';13import workerFileUrl from 'fast-check-monorepo/dist/lib/workerFileUrl.mjs';14import workerFileUrl from 'fast-check/dist/lib/workerFileUrl.mjs';15import workerFileUrl from 'fast-check-monorepo/dist/lib/workerFileUrl.cjs';16import workerFileUrl from 'fast-check/dist/lib/workerFileUrl.cjs
Using AI Code Generation
1const workerFileUrl = require('fast-check').workerFileUrl;2const workerPath = workerFileUrl('./worker.js');3const worker = new Worker(workerPath, { type: 'module' });4worker.on('message', (message) => console.log(`Worker said: ${message}`));5worker.postMessage('hello');6const workerFileUrl = require('fast-check').workerFileUrl;7const workerPath = workerFileUrl('./worker.js');8const worker = new Worker(workerPath, { type: 'module' });9worker.on('message', (message) => console.log(`Worker said: ${message}`));10worker.postMessage('hello');11const { parentPort } = require('worker_threads');12parentPort.on('message', (message) => {13 console.log(`Parent said: ${message}`);14 parentPort.postMessage(`Hi! I am the worker, and I received your message: ${message}`);15});16parentPort.postMessage('Hello! I am the worker, and I received your message');17const { parentPort } = require('worker_threads');18parentPort.on('message', (message) => {19 console.log(`Parent said: ${message}`);20 parentPort.postMessage(`Hi! I am the worker, and I received your message: ${message}`);21});22parentPort.postMessage('Hello! I am the worker, and I received your message');23const { parentPort } = require('worker_threads');24parentPort.on('message', (message) => {25 console.log(`Parent said: ${message}`);26 parentPort.postMessage(`Hi! I am the worker, and I received your message: ${message}`);27});28parentPort.postMessage('Hello! I am the worker, and I received your message');29const { parentPort } = require('worker_threads');30parentPort.on('message', (message) => {
Using AI Code Generation
1const workerFileUrl = require('fast-check-monorepo').workerFileUrl;2const workerUrl = workerFileUrl('worker.js');3const worker = new Worker(workerUrl);4worker.on('message', (message) => {5 console.log(message);6});7worker.on('error', (err) => {8 console.error(err);9});10worker.postMessage('hello');11const workerFileUrl = require('fast-check-monorepo').workerFileUrl;12const workerUrl = workerFileUrl('worker.js');13self.on('message', (message) => {14 self.postMessage(message);15});16self.on('error', (err) => {17 console.error(err);18});
Using AI Code Generation
1const workerFileUrl = require("fast-check").workerFileUrl;2const workerUrl = workerFileUrl(__dirname, "worker.js");3const workerFileUrl = require("fast-check").workerFileUrl;4const workerUrl = workerFileUrl(__dirname, "worker.js");5const fc = require("fast-check");6const { workerData, parentPort } = require("worker_threads");7fc.configureGlobal({ numRuns: 1000 });8fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b === b + a), {
Using AI Code Generation
1import { workerFileUrl } from "fast-check-monorepo";2const workerUrl = workerFileUrl("worker.js");3const worker = new Worker(workerUrl);4worker.postMessage("hello");5worker.onmessage = (e) => console.log(e.data);6worker.onerror = (e) => console.log(e.error);7self.onmessage = (e) => self.postMessage(e.data + " world");
Using AI Code Generation
1const workerFileUrl = require('fast-check-monorepo').workerFileUrl;2const worker = new Worker(workerFileUrl('worker.js'));3worker.postMessage('hello');4worker.onmessage = (e) => console.log('Received:', e.data);5onmessage = (e) => {6 console.log('Received:', e.data);7 postMessage('hello back');8};9const path = require('path');10const workerFileUrl = require('fast-check-monorepo').workerFileUrl;11module.exports = {12 output: {13 publicPath: (url, resourcePath) => {14 return workerFileUrl(url, resourcePath);15 },16 },17};
Using AI Code Generation
1import { workerFileUrl } from 'fast-check-monorepo';2const worker = new Worker(workerFileUrl('worker.js'));3worker.postMessage('hello');4self.onmessage = function (e) {5 self.postMessage('You said: ' + e.data);6};7worker.onmessage = function (e) {8 console.log('Worker said: ' + e.data);9};10function workerFileUrl(workerFile: string): string;11import { workerFileUrl } from 'fast-check-monorepo';12const worker = new Worker(workerFileUrl('worker.js'));13[MIT](LICENSE)
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!!