Best JavaScript code snippet using cypress
cli.js
Source:cli.js
...17 client,18 workers = {},19 workerKeys = {},20 tunnelingAgent;21function terminateAllWorkers(callback) {22 logger.trace('terminateAllWorkers');23 var cleanWorker = function(id, key) {24 logger.trace('cleanWorker(%s, %s)', id, key);25 client.terminateWorker(id, function() {26 var worker = workers[key];27 if(worker) {28 logger.debug('[%s] Terminated', worker.string);29 clearTimeout(worker.ackTimeout);30 clearTimeout(worker.activityTimeout);31 clearTimeout(worker.testActivityTimeout);32 delete workers[key];33 delete workerKeys[worker.id];34 }35 if (utils.objectSize(workers) === 0) {36 logger.trace('terminateAllWorkers: done');37 callback();38 }39 });40 };41 if (utils.objectSize(workers) === 0) {42 logger.trace('terminateAllWorkers: done');43 callback();44 } else {45 for (var key in workers){46 var worker = workers[key];47 if (worker.id) {48 cleanWorker(worker.id, key);49 } else {50 delete workers[key];51 if (utils.objectSize(workers) === 0) {52 logger.trace('terminateAllWorkers: done');53 callback();54 }55 }56 }57 }58}59function cleanUpAndExit(signal, error, report, callback) {60 ConfigParser.finalBrowsers = [];61 callback = callback || function() {};62 report = report || [];63 logger.trace('cleanUpAndExit: signal: %s', signal);64 try {65 server.close();66 } catch (e) {67 logger.debug('Server already closed');68 }69 if (statusPoller) {70 statusPoller.stop();71 }72 try {73 process.kill(tunnel.process.pid, 'SIGTERM');74 } catch (e) {75 logger.debug('Non existent tunnel');76 }77 if (signal === 'SIGTERM') {78 logger.debug('Exiting');79 callback(error, report);80 } else {81 terminateAllWorkers(function() {82 logger.debug('Exiting');83 callback(error, report);84 });85 }86}87function getTestBrowserInfo(browserString, path) {88 var info = browserString;89 if (config.multipleTest) {90 info += ', ' + path;91 }92 logger.trace('getTestBrowserInfo(%s, %s): %s', browserString, path, info);93 return info;94}95function buildTestUrl(test_path, worker_key, browser) {...
createWorkers.js
Source:createWorkers.js
...90 })91 worker.nodeWorker.once("exit", () => {92 // happens when:93 // - terminate is called due to error when calling worker.postMessage()94 // - terminate is called by terminateAllWorkers()95 // - terminate is called because job is cancelled while worker is executing96 // - terminate is called because worker timeout during execution97 // - There is a runtime error during job excecution98 // -> These cases should be catched by workerMap.has(worker.id)99 // - There is a runtime error during worker execution100 if (workerMap.has(worker.id)) {101 logger.debug(`worker #${worker.id} exited, it's not supposed to happen`)102 forget(worker)103 }104 // the worker emitted an "error" event outside the execution of a job105 // this is not supposed to happen and is used to recognize worker106 // throwing a top level error. In that case we don't want to create107 // an other worker that would also throw108 if (worker.errored) {109 logger.debug(`this worker won't be replace (errored flag is true)`)110 return111 }112 const workerCount = workerMap.size113 if (workerCount >= minWorkers) {114 logger.debug(115 `this worker won't be replaced (there is enough worker already: ${workerCount})`,116 )117 return118 }119 logger.debug("adding a new worker to replace the one who exited")120 addWorker()121 })122 return worker123 }124 const addWorker = () => {125 const newWorker = createWorker()126 tryToGoIdle(newWorker)127 }128 const tryToGoIdle = (worker) => {129 const nextJob = jobsWaitingAnAvailableWorker.shift()130 if (nextJob) {131 assignJobToWorker(nextJob, worker)132 return133 }134 markAsIdle(worker)135 }136 const markAsIdle = (worker) => {137 removeFromArray(busyArray, worker.id)138 idleArray.push(worker.id)139 logger.debug(`worker#${worker.id} marked as "idle"`)140 const workerCount = workerMap.size141 if (142 // keep the min amount of workers alive143 workerCount <= minWorkers ||144 // or if they are allowd to live forever145 maxIdleDuration === Infinity146 ) {147 return148 }149 // this worker was dynamically added, remove it according to maxIdleDuration150 worker.idleKillTimeout = setTimeout(() => {151 logger.debug(152 `killing worker #${worker.id} because idle during more than "maxIdleDuration" (${maxIdleDuration}ms)`,153 )154 kill(worker)155 }, maxIdleDuration)156 worker.idleKillTimeout.unref()157 }158 const addJob = (159 jobData,160 { transferList = [], abortSignal, allocatedMs } = {},161 ) => {162 return new Promise((resolve, reject) => {163 const job = {164 id: jobIdGenerator(),165 data: jobData,166 transferList,167 allocatedMs,168 abortSignal,169 reject,170 resolve,171 }172 logger.debug(`add job#${job.id}`)173 if (abortSignal && abortSignal.aborted) {174 reject(new Error(`job#${job.id} already aborted`))175 return176 }177 if (idleArray.length > 0) {178 logger.debug(`a worker is available for that job`)179 assignJobToWorker(job, workerMap.get(idleArray[0]))180 return181 }182 const workerCount = workerMap.size183 if (workerCount < maxWorkers) {184 logger.debug(`adding a worker for that job`)185 const worker = createWorker()186 assignJobToWorker(job, worker)187 return188 }189 const jobWaitingCount = jobsWaitingAnAvailableWorker.length190 if (jobWaitingCount > maxWaitingJobs) {191 throw new Error(192 `maxWaitingJobs reached (${maxWaitingJobs}), cannot add more job`,193 )194 }195 logger.debug(196 `no worker available for that job -> waiting for an available worker`,197 )198 jobsWaitingAnAvailableWorker.push(job)199 if (abortSignal) {200 const unregisterAbort = registerEventCallback(201 abortSignal,202 "abort",203 () => {204 unregisterAbort()205 removeFromArray(jobsWaitingAnAvailableWorker, job)206 reject(new Error(`job#${job.id} aborted while waiting a worker`))207 },208 )209 job.unregisterAbort = unregisterAbort210 }211 })212 }213 const assignJobToWorker = async (job, worker) => {214 // make worker busy215 clearTimeout(worker.idleKillTimeout)216 removeFromArray(idleArray, worker.id)217 busyArray.push(worker.id)218 job.worker = worker219 worker.job = job220 logger.debug(`job #${job.id} assigned to worker #${worker.id}`)221 // creating an async ressource is important so that Node.js222 // knows we are doing async stuff223 // without this the process sometimes hangs forever224 // https://nodejs.org/dist/latest-v16.x/docs/api/async_context.html#async_context_using_asyncresource_for_a_worker_thread_pool225 const asyncRessource = new AsyncResource(`job#${job.id}`, {226 triggerAsyncId: executionAsyncId(),227 requireManualDestroy: true,228 })229 const resolve = (value) => {230 asyncRessource.runInAsyncScope(() => {}, null, null, value)231 asyncRessource.emitDestroy()232 job.resolve(value)233 }234 const reject = (e) => {235 asyncRessource.runInAsyncScope(() => {}, null, e)236 asyncRessource.emitDestroy()237 job.reject(e)238 }239 let onPostMessageError240 const raceWinnerPromise = raceCallbacks({241 timeout: (cb) => {242 if (!job.allocatedMs) {243 return null244 }245 const timeout = setTimeout(cb, job.allocatedMs)246 return () => {247 clearTimeout(timeout)248 }249 },250 abort: (cb) => {251 if (!job.abortSignal) {252 return null253 }254 // abort now have a new effect: it's not anymore just255 // removing job from "jobsWaitingAnAvailableWorker"256 job.unregisterAbort()257 return registerEventCallback(job.abortSignal, "abort", cb)258 },259 error: (cb) => registerEventCallback(worker.nodeWorker, "error", cb),260 messageerror: (cb) =>261 registerEventCallback(worker.nodeWorker, "messageerror", cb),262 exit: (cb) => registerEventCallback(worker.nodeWorker, "exit", cb),263 message: (cb) => registerEventCallback(worker.nodeWorker, "message", cb),264 postMessageError: (cb) => {265 onPostMessageError = cb266 },267 })268 try {269 worker.nodeWorker.postMessage(job.data, job.transferList)270 } catch (e) {271 onPostMessageError(e) // to ensure other callbacks are removed by raceCallbacks272 }273 const winner = await raceWinnerPromise274 worker.job = null275 const callbacks = {276 // likely postMessageError.name ==="DataCloneError"277 postMessageError: (postMessageError) => {278 worker.job = job279 reject(postMessageError)280 // we call worker.terminate otherwise the process never exits281 kill(worker)282 },283 // uncaught error throw in the worker:284 // - clear timeout285 // - calls job.onError, the job promise will be rejected286 // - worker will be removed by "exit" listener set in "createWorker"287 error: (error) => {288 worker.job = job289 reject(error)290 },291 // Error occured while deserializing a message sent by us to the worker292 // - clear timeout293 // - calls job.onMessageError, the job promise will be rejected294 // - indicate worker is about to be idle295 messageerror: (error) => {296 reject(error)297 tryToGoIdle(worker)298 },299 abort: () => {300 // The worker might be in the middle of something301 // it cannot be reused, we terminate it302 kill(worker)303 reject(new Error(`job#${job.id} aborted during execution by worker`))304 },305 timeout: () => {306 // Same here, worker is in the middle of something, kill it307 kill(worker)308 reject(309 new Error(310 `worker timeout: worker #${job.worker.id} is too slow to perform job #${job.id} (takes more than ${job.allocatedMs} ms)`,311 ),312 )313 },314 // Worker exits before emitting a "message" event, this is unexpected315 // - clear timeout316 // - calls job.onExit, the job promise will be rejected317 // - worker will be removed by "exit" listener set in "createWorker"318 exit: (exitCode) => {319 reject(320 new Error(321 `worker exited: worker #${job.worker.id} exited with code ${exitCode} while performing job #${job.id}.`,322 ),323 )324 },325 // Worker properly respond something326 // - clear timeout327 // - call job.onMessage, the job promise will resolve328 // - indicate worker is about to be idle329 message: (value) => {330 logger.debug(`job #${job.id} completed`)331 resolve(value)332 tryToGoIdle(worker)333 },334 }335 callbacks[winner.name](winner.data)336 }337 const terminateAllWorkers = async () => {338 logger.debug(`terminal all workers`)339 await Promise.allSettled(340 Array.from(workerMap.values()).map(async (worker) => {341 await worker.terminate()342 }),343 )344 }345 let unregisterSIGINT = () => {}346 const destroy = async () => {347 unregisterSIGINT()348 minWorkers = 0 // prevent onWorkerExit() to spawn worker349 maxWorkers = 0 // so that if any code calls addJob, new worker are not spawned350 jobsWaitingAnAvailableWorker.length = 0351 await terminateAllWorkers()352 workerMap.clear() // this is to help garbage collect faster but not required353 }354 if (handleSIGINT) {355 const SIGINTCallback = () => {356 logger.debug(`SIGINT`)357 destroy()358 }359 process.once("SIGINT", SIGINTCallback)360 unregisterSIGINT = () => {361 process.removeListener("SIGINT", SIGINTCallback)362 }363 }364 if (minWorkers > 0) {365 let numberOfWorkerToCreate = Math.ceil(minWorkers)...
mandelbrot-xdk-ww.js
Source:mandelbrot-xdk-ww.js
...155 var mw = mWorkers [mWorkerCount-1];156 mw.wworker.postMessage({terminate:true}); 157 mWorkerCount--;158 }159 function terminateAllWorkers() {160 while (mWorkerCount > 0) {161 terminateLastWorker ();162 }163 }164 function numberOfWorkers() {165 return mWorkerCount;166 }167 function bufferOf(worker_index) {168 return mWorkers[worker_index].buffer;169 }170 function workerIsActive(worker_index) {171 return worker_index < mWorkerCount;172 }173 return {...
mandelbrot-ww.js
Source:mandelbrot-ww.js
...130 var mw = mWorkers [mWorkerCount-1];131 mw.wworker.postMessage({terminate:true});132 mWorkerCount--;133 }134 function terminateAllWorkers() {135 while (mWorkerCount > 0) {136 terminateLastWorker ();137 }138 }139 function numberOfWorkers() {140 return mWorkerCount;141 }142 function bufferOf(worker_index) {143 return mWorkers[worker_index].buffer;144 }145 function workerIsActive(worker_index) {146 return worker_index < mWorkerCount;147 }148 return {...
mandelbrot-ww-asm.js
Source:mandelbrot-ww-asm.js
...125 var mw = mWorkers [mWorkerCount-1];126 mw.wworker.postMessage({terminate:true});127 mWorkerCount--;128 }129 function terminateAllWorkers() {130 while (mWorkerCount > 0) {131 terminateLastWorker ();132 }133 }134 function numberOfWorkers() {135 return mWorkerCount;136 }137 function bufferOf(worker_index) {138 return mWorkers[worker_index].buffer;139 }140 function workerIsActive(worker_index) {141 return worker_index < mWorkerCount;142 }143 return {...
provider_test.js
Source:provider_test.js
...119 demand: 10,120 });121 await subject.rejectBids({bids});122 });123 test('.terminateAllWorkers() should work as specified', async () => {124 await subject.terminateAllWorkers();125 });126 test('.terminateWorkerType() should work as specified', async () => {127 await subject.terminateWorkerType({workerType});128 });129 test('.terminateWorker() should work as specified', async () => {130 let [worker] = await subject.listWorkers({131 states: [Provider.running],132 workerTypes: [workerType],133 });134 await subject.terminateWorker({workers: [worker]});135 await subject.terminateWorker({workers: [worker.id]});136 });137 });138}...
manager.js
Source:manager.js
...52 this.calculatePI();53 this.callAllUpdateListeners();54 if (this.targetTotalPointCount === this.calculatedPointCount) {55 this.callAllCompleteListeners();56 this.terminateAllWorkers();57 }58 }59 terminateAllWorkers() {60 this.workers.forEach(worker => worker.terminate());61 this.workers = [];62 }63 addNewWorker() {64 const worker = new Worker("./worker.js");65 this.workers.push(worker);66 worker.onmessage = this.workerMessageHandler;67 }68 runWorker(worker, pointWorkLoad) {69 worker.postMessage({ pointWorkLoad });70 }71 runAllWorkers() {72 const pointWorkLoads = this.getPointWorkLoads();73 this.workers.forEach((worker, i) => this.runWorker(worker, pointWorkLoads[i]));...
index.js
Source:index.js
1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3exports.terminateAllWorkers = exports.createInitialWorkers = exports.DeferredSourceMapCache = exports.rewriteHtmlJsAsync = exports.rewriteJsAsync = exports.HtmlJsRewriter = void 0;4var html_1 = require("./html");5Object.defineProperty(exports, "HtmlJsRewriter", { enumerable: true, get: function () { return html_1.HtmlJsRewriter; } });6var async_rewriters_1 = require("./async-rewriters");7Object.defineProperty(exports, "rewriteJsAsync", { enumerable: true, get: function () { return async_rewriters_1.rewriteJsAsync; } });8Object.defineProperty(exports, "rewriteHtmlJsAsync", { enumerable: true, get: function () { return async_rewriters_1.rewriteHtmlJsAsync; } });9var deferred_source_map_cache_1 = require("./deferred-source-map-cache");10Object.defineProperty(exports, "DeferredSourceMapCache", { enumerable: true, get: function () { return deferred_source_map_cache_1.DeferredSourceMapCache; } });11var threads_1 = require("./threads");12Object.defineProperty(exports, "createInitialWorkers", { enumerable: true, get: function () { return threads_1.createInitialWorkers; } });...
Using AI Code Generation
1Cypress.config('experimentalSourceRewriting', true);2Cypress.on('window:before:load', win => {3 win.terminateAllWorkers = () => {4 win.navigator.serviceWorker.getRegistrations().then(registrations => {5 for (const registration of registrations) {6 registration.unregister();7 }8 });9 };10});11Cypress.Commands.add('terminateAllWorkers', () => {12 cy.window().then(win => {13 win.terminateAllWorkers();14 });15});16Cypress.on('window:load', win => {17 win.terminateAllWorkers();18});19Cypress.on('window:before:unload', win => {20 win.terminateAllWorkers();21});22Cypress.on('window:unload', win => {23 win.terminateAllWorkers();24});25Cypress.on('window:before:load', win => {26 win.terminateAllWorkers();27});28Cypress.on('window:load', win => {29 win.terminateAllWorkers();30});31Cypress.on('window:before:unload', win => {32 win.terminateAllWorkers();33});34Cypress.on('window:unload', win => {35 win.terminateAllWorkers();36});37Cypress.on('window:before:load', win => {38 win.terminateAllWorkers();39});40Cypress.on('window:load', win => {41 win.terminateAllWorkers();42});43Cypress.on('window:before:unload', win => {44 win.terminateAllWorkers();45});46Cypress.on('window:unload', win => {47 win.terminateAllWorkers();48});49Cypress.on('window:before:load', win => {50 win.terminateAllWorkers();51});52Cypress.on('window:load', win => {53 win.terminateAllWorkers();54});
Using AI Code Generation
1Cypress.on('window:before:load', (win) => {2 win.terminateAllWorkers = () => {3 const workers = win.navigator.serviceWorker.getRegistrations()4 workers.then((registrations) => {5 registrations.forEach((registration) => registration.unregister())6 })7 }8})9beforeEach(function() {10 cy.window().then((win) => {11 win.terminateAllWorkers()12 })13})14{15 "env": {16 }17}18module.exports = (on, config) => {19 on("before:browser:launch", (browser = {}, launchOptions) => {20 if (browser.family === "chromium" && browser.name !== "electron") {21 launchOptions.args.push("--disable-features=CrossSiteDocumentBlockingAlways,CrossSiteDocument
Using AI Code Generation
1cy.task('terminateAllWorkers');2cy.wait(1000);3cy.task('terminateWorker', 0);4cy.wait(1000);5cy.task('terminateWorker', 1);6cy.wait(1000);7cy.task('terminateWorker', 2);8cy.wait(1000);9cy.task('terminateWorker', 3);10cy.wait(1000);11cy.task('terminateWorker', 4);12cy.wait(1000);13cy.task('terminateWorker', 5);14cy.wait(1000);15cy.task('terminateWorker', 6);16cy.wait(1000);17cy.task('terminateWorker', 7);18cy.wait(1000);19cy.task('terminateWorker', 8);20cy.wait(1000);21cy.task('terminateWorker', 9);22cy.wait(1000);23cy.task('terminateWorker', 10);24cy.wait(1000);25cy.task('terminateWorker', 11);26cy.wait(1000);27cy.task('terminateWorker', 12);28cy.wait(1000);29cy.task('terminateWorker', 13);30cy.wait(1000);31cy.task('terminateWorker', 14);32cy.wait(1000);33cy.task('terminateWorker', 15);34cy.wait(1000);35cy.task('terminateWorker', 16);36cy.wait(1000);37cy.task('terminateWorker', 17);38cy.wait(1000);39cy.task('terminateWorker', 18);40cy.wait(1000);
Using AI Code Generation
1const cypress = require('cypress');2cypress.run({3 env: {4 },5 reporterOptions: {6 }7}).then((results) => {8 console.log('Tests completed, terminating workers');9 cypress.terminalAllWorkers();10}).catch((err) => {11 console.log(err);12 cypress.terminalAllWorkers();13});14module.exports = (on, config) => {15 on('task', {16 terminateWorkers: () => {17 console.log('Terminating workers from plugins');18 cypress.terminalAllWorkers();19 return null;20 }21 });22}23describe('Test', () => {24 it('Test', () => {25 cy.task('terminateWorkers');26 });27});28I have also tried this on both the latest version of Mochawesome-report-generator (4
Using AI Code Generation
1const cypress = require('cypress');2cypress.run({3}).then((result) => {4 if (result.totalFailed > 0) {5 cypress.runner.stop();6 }7}).catch((err) => {8 console.error(err);9 cypress.runner.stop();10});11describe('Worker Test', () => {12 it('worker test', () => {13 cy.get('#launch').click();14 cy.get('#message').should('contain', 'Worker has responded');15 });16});
Using AI Code Generation
1cy.then(() => {2 cy.terminateAllWorkers();3})4Cypress.Commands.add('terminateAllWorkers', () => {5 const workerPool = Cypress.automation('remote:debugger:protocol', {6 })7 workerPool.then((workers) => {8 workers.forEach(worker => {9 Cypress.automation('remote:debugger:protocol', {10 params: { workerId: worker.id }11 })12 })13 })14})15import './commands'16module.exports = (on, config) => {17}18{19 "reporterOptions": {20 },21}22{23 "scripts": {24 },25 "devDependencies": {
Using AI Code Generation
1cy.task('terminateAllWorkers', {force: true}).then(() => {2 cy.log('All workers terminated')3})4module.exports = (on, config) => {5 on('task', {6 terminateAllWorkers: () => {7 const cypress = require('cypress')8 cypress.runner.stop()9 }10 })11}
Using AI Code Generation
1Cypress.on('window:before:load', (win) => {2 win.Cypress = {3 terminateAllWorkers: () => {4 }5 }6})7beforeEach(() => {8 cy.window().then((win) => {9 win.Cypress = {10 terminateAllWorkers: () => {11 }12 }13 })14})15afterEach(() => {16 cy.window().then((win) => {17 win.Cypress = {18 terminateAllWorkers: () => {19 }20 }21 })22})23after(() => {24 cy.window().then((win) => {25 win.Cypress = {26 terminateAllWorkers: () => {27 }28 }29 })30})31afterEach(() => {32 cy.window().then((win) => {33 win.Cypress = {34 terminateAllWorkers: () => {35 }36 }37 })38})39afterEach(() => {
Using AI Code Generation
1const cypress = require('cypress');2const { spawn } = require('child_process');3module.exports = async (on, config) => {4 on('task', {5 async terminateAllWorkers() {6 console.log('in terminateAllWorkers');7 cypress.terminalLog('in terminateAllWorkers');8 const child = spawn('pkill', ['node']);9 child.stderr.on('data', (data) => {10 console.error(`stderr: ${data}`);11 });12 child.on('close', (code) => {13 console.log(`child process exited with code ${code}`);14 });15 return null;16 },17 });18};19Cypress.on('window:before:load', (win) => {20 win.terminateAllWorkers = () => {21 console.log('in terminateAllWorkers');22 cy.task('terminateAllWorkers');23 };24});25describe('My First Test', () => {26 it('Does not do much!', () => {27 cy.contains('type').click();28 cy.url().should('include', '/commands/actions');29 cy.get('.action-email')30 .type('
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!