Best JavaScript code snippet using cypress
queue.spec.js
Source: queue.spec.js
...155 describe('#shutdownWorker', function() {156 it('should remove worker', function() {157 var q = new th.Queue(th.testRef, _.noop);158 expect(q.getWorkerCount()).to.equal(1);159 q.shutdownWorker();160 expect(q.getWorkerCount()).to.equal(0);161 });162 it('should shutdown worker', function() {163 var q = new th.Queue(th.testRef, _.noop);164 expect(q.getWorkerCount()).to.equal(1);165 var workerShutdownPromise = q.shutdownWorker();166 return workerShutdownPromise;167 });168 it('should reject when no workers remaining', function() {169 var q = new th.Queue(th.testRef, _.noop);170 expect(q.getWorkerCount()).to.equal(1);171 q.shutdownWorker();172 return q.shutdownWorker().catch(function(error) {173 expect(error.message).to.equal('No workers to shutdown');174 });175 });176 });177 describe('#shutdown', function() {178 var q;179 it('should shutdown a queue initialized with the default spec', function() {180 q = new th.Queue(th.testRef, _.noop);181 return q.shutdown().should.eventually.be.fulfilled;182 });183 it('should shutdown a queue initialized with a custom spec before the listener callback', function() {184 q = new th.Queue(th.testRef, { specId: 'test_task' }, _.noop);185 return q.shutdown().should.eventually.be.fulfilled;186 });...
index.js
Source: index.js
...115}116exports.createInitialWorkers = createInitialWorkers;117// try to cleanly shut down worker threads to avoid SIGABRT in Electron118// @see https://github.com/electron/electron/issues/23366119function shutdownWorker(workerInfo) {120 const { thread } = workerInfo;121 return new bluebird_1.default((resolve) => {122 thread.once('exit', resolve);123 thread.once('error', resolve);124 thread.postMessage({ shutdown: true });125 })126 .timeout(100)127 .catch((err) => {128 debug('error cleanly shutting down worker, terminating from parent %o', { err, workerInfo: _debugWorker(workerInfo) });129 return thread.terminate();130 });131}132exports.shutdownWorker = shutdownWorker;133function terminateAllWorkers() {...
main.js
Source: main.js
...178 process.send({ cmd: 'worker_shutdown', pid: process.pid });179 };180 sockDomain.on('error', function(error) {181 helpers.logError(workerName, 'Socket HTTP server error: '+error);182 shutdownWorker();183 });184 httpDomain.on('error', function(error) {185 helpers.logError(workerName, 'HTTP server error: '+error);186 shutdownWorker();187 });...
ClusterManager.js
Source: ClusterManager.js
...92 worker.removeOldWorker = setTimeout(function() {93 if (shutdownArray.length > 0) {94 var workerToShutdown = shutdownArray.pop();95 log('New worker[' + worker.id + '] has been up for ' + timeoutBeforeShutdown + 'ms. Asking worker[' + workerToShutdown.id + '] to shutdown');96 shutdownWorker(workerToShutdown);97 }98 }, timeoutBeforeShutdown);99 });100 process.on('SIGHUP', function SIGHUP() {101 log('Rolling restarting request received');102 if (!fs.existsSync(options.exec)) {103 log('File ' + options.exec + " does not exist. Won't restart.", true);104 if (notify !== null) {105 sendNotification(notify, '[' + hostname + '] File ' + options.exec + ' does not exist. Wont restart.', runningWorkersMsg()); // eslint-disable-line no-use-before-define106 }107 return;108 }109 if (notify !== null) {110 sendNotification(notify, '[' + hostname + '] Rolling restart of instances', runningWorkersMsg()); // eslint-disable-line no-use-before-define111 }112 var currentTotal;113 var currentWorkers = Object.keys(cluster.workers);114 var workerID;115 var worker;116 for (currentTotal = 0; currentTotal < numWorkers; currentTotal++) {117 log('Spawning new process...');118 cluster.fork();119 if (currentWorkers.length > 0) {120 workerID = currentWorkers.pop();121 worker = cluster.workers[workerID];122 shutdownArray.push(worker);123 }124 }125 for (workerID in currentWorkers) {126 worker = cluster.workers[currentWorkers[workerID]];127 log('Removing excess workers: ' + worker.id);128 shutdownWorker(worker);129 }130 });131 process.on('SIGUSR1', function SIGUSR1() {132 log(runningWorkersMsg(), true);133 });134 process.on('SIGUSR2', function SIGUSR2() {135 var currentWorkers = Object.keys(cluster.workers).length;136 log('Workers running: ' + currentWorkers + ' - Max Workers: ' + numWorkers);137 if (currentWorkers < numWorkers) {138 log('Starting ' + (numWorkers - currentWorkers) + ' worker(s)');139 for (var currentTotal = 0; currentTotal < (numWorkers - currentWorkers); currentTotal++) {140 cluster.fork();141 }142 }143 log(runningWorkersMsg());144 });145 process.on('SIGTERM', function SIGTERM() {146 log('Termination request received');147 if (notify !== null) {148 sendNotification(notify, '[' + hostname + '] Shutting down all worker instances', runningWorkersMsg()); // eslint-disable-line no-use-before-define149 }150 var currentWorkers = Object.keys(cluster.workers);151 for (var workerID in currentWorkers) {152 var worker = cluster.workers[currentWorkers[workerID]];153 shutdownWorker(worker);154 }155 });156 cluster.fork = function() {157 if (!fs.existsSync(cluster.settings.exec)) {158 console.error('File ' + cluster.settings.exec + " does not exist. Won't FORK.");159 if (notify !== null) {160 sendNotification(notify, '[' + hostname + '] File ' + cluster.settings.exec + ' does not exist. Wont FORK.', runningWorkersMsg()); // eslint-disable-line no-use-before-define161 }162 return;163 }164 origFork.bind(this)();165 };166 log('Master process PID is ' + process.pid);167 if (pidfile !== null) {...
server.js
Source:server.js
1#!/usr/bin/env node2/**3 * Cluster-based Parsoid web service runner. Implements4 * https://www.mediawiki.org/wiki/Parsoid#The_Parsoid_web_API5 *6 * Local configuration:7 *8 * To configure locally, add localsettings.js to this directory and export a9 * setup function.10 *11 * example:12 * exports.setup = function(parsoidConfig) {13 * parsoidConfig.setMwApi('localhost', { uri: 'http://localhost/wiki' });14 * };15 *16 * (See localsettings.js.example for more options to setMwApi.)17 * Alternatively, specify a --config file explicitly. See --help for other18 * options.19 *20 * See https://www.mediawiki.org/wiki/Parsoid/Setup for more instructions.21 */22'use strict';23require('../lib/core-upgrade.js');24var cluster = require('cluster');25var path = require('path');26var util = require('util');27var fs = require('fs');28// process arguments29var opts = require("yargs")30 .usage("Usage: $0 [-h|-v] [--param[=val]]")31 .default({32 // Start a few more workers than there are cpus visible to the OS,33 // so that we get some degree of parallelism even on single-core34 // systems. A single long-running request would otherwise hold up35 // all concurrent short requests.36 n: require("os").cpus().length + 3,37 c: __dirname + '/localsettings.js',38 v: false,39 h: false,40 })41 .boolean([ "h", "v" ])42 .alias("h", "help")43 .alias("v", "version")44 .alias("c", "config")45 .alias("n", "num-workers");46// Help47var argv = opts.argv;48if (argv.h) {49 opts.showHelp();50 process.exit(0);51}52// Version53var meta = require(path.join(__dirname, "../package.json"));54if (argv.v) {55 console.log(meta.name + " " + meta.version);56 process.exit(0);57}58var ParsoidService = require("./ParsoidService.js").ParsoidService;59var ParsoidConfig = require("../lib/mediawiki.ParsoidConfig").ParsoidConfig;60var Logger = require("../lib/Logger.js").Logger;61var PLogger = require("../lib/ParsoidLogger.js");62var ParsoidLogger = PLogger.ParsoidLogger;63var ParsoidLogData = PLogger.ParsoidLogData;64// The global parsoid configuration object65var lsp = path.resolve(process.cwd(), argv.c);66var localSettings;67try {68 localSettings = require(lsp);69} catch (e) {70 console.error(71 "Cannot load local settings from %s. Please see: %s",72 lsp, path.join(__dirname, "localsettings.js.example")73 );74 process.exit(1);75}76var parsoidConfig = new ParsoidConfig(localSettings, null);77var locationData = {78 process: {79 name: cluster.isMaster ? "master" : "worker",80 pid: process.pid,81 },82 toString: function() {83 return util.format("[%s][%s]", this.process.name, this.process.pid);84 },85};86// Setup process logger87var logger = new Logger();88logger._createLogData = function(logType, logObject) {89 return new ParsoidLogData(logType, logObject, locationData);90};91logger._defaultBackend = ParsoidLogger.prototype._defaultBackend;92ParsoidLogger.prototype.registerLoggingBackends.call(93 logger, [ "fatal", "error", "warning", "info" ], parsoidConfig94);95process.on('uncaughtException', function(err) {96 logger.log('fatal', 'uncaught exception', err);97});98if (cluster.isMaster && argv.n > 0) {99 // Master100 var timeoutHandler;101 var timeouts = new Map();102 var spawn = function() {103 var worker = cluster.fork();104 worker.on('message', timeoutHandler.bind(null, worker));105 };106 // Kill cpu hogs107 timeoutHandler = function(worker, msg) {108 if (msg.type === 'startup') {109 // relay startup messages to parent process110 if (process.send) { process.send(msg); }111 }112 if (msg.type !== "timeout") { return; }113 if (msg.done) {114 clearTimeout(timeouts.get(msg.timeoutId));115 timeouts.delete(msg.timeoutId);116 } else if (msg.timeout) {117 var pid = worker.process.pid;118 timeouts.set(msg.timeoutId, setTimeout(function() {119 timeouts.delete(msg.timeoutId);120 if (worker.id in cluster.workers) {121 logger.log("warning", util.format(122 "Cpu timeout fetching: %s; killing worker %s.",123 msg.location, pid124 ));125 worker.kill("SIGKILL");126 spawn();127 }128 }, msg.timeout));129 }130 };131 // Fork workers132 var worker;133 logger.log("info", util.format("initializing %s workers", argv.n));134 for (var i = 0; i < argv.n; i++) {135 spawn();136 }137 cluster.on('exit', function(worker, code, signal) {138 if (!worker.suicide) {139 var pid = worker.process.pid;140 logger.log("warning", util.format("worker %s died (%s), restarting.", pid, code));141 spawn();142 }143 });144 var shutdownMaster = function() {145 logger.log("info", "shutting down, killing workers");146 cluster.disconnect(function() {147 logger.log("info", "exiting");148 process.exit(0);149 });150 };151 process.on('SIGINT', shutdownMaster);152 process.on('SIGTERM', shutdownMaster);153} else {154 // Worker155 var shutdownWorker = function() {156 logger.log("warning", "shutting down");157 process.exit(0);158 };159 process.on('SIGTERM', shutdownWorker);160 process.on('disconnect', shutdownWorker);161 // Enable heap dumps in /tmp on kill -USR2.162 // See https://github.com/bnoordhuis/node-heapdump/163 // For node 0.6/0.8: npm install heapdump@0.1.0164 // For 0.10: npm install heapdump165 process.on('SIGUSR2', function() {166 var heapdump = require('heapdump');167 logger.log("warning", "SIGUSR2 received! Writing snapshot.");168 process.chdir('/tmp');169 heapdump.writeSnapshot();170 });171 // Send heap usage statistics to Graphite at the requested sample rate172 if (parsoidConfig.performanceTimer && parsoidConfig.heapUsageSampleInterval) {173 setInterval(function() {174 var heapUsage = process.memoryUsage();175 parsoidConfig.performanceTimer.timing('heap.rss', '', heapUsage.rss);176 parsoidConfig.performanceTimer.timing('heap.total', '', heapUsage.heapTotal);177 parsoidConfig.performanceTimer.timing('heap.used', '', heapUsage.heapUsed);178 }, parsoidConfig.heapUsageSampleInterval);179 }180 var app = new ParsoidService(parsoidConfig, logger);...
Worker.js
Source:Worker.js
1var Asimov = require('./Asimov');2module.exports = Asimov.extend({3 'start': function (next) {4 var self = this;5 if (self.running) return;6 self.running = true;7 self._publicInterface.register = function () {8 throw new Error('Cannot register public interface after calling asimov.start()');9 };10 var started = new Date();11 process.on('message', self.onMessage);12 process.on('exit', self.shutdownWorker);13 process.on('SIGHUP', self.shutdownWorker);14 process.on('SIGTERM', self.shutdownWorker);15 process.on('SIGINT', self.shutdownWorker);16 var amount = self.getSequence('preinit').length + self.getSequence('init').length + self.getSequence('postinit').length;17 if (!amount) {18 self.publish('app:started');19 process.send && process.send({20 'event': 'app:started',21 'initializers': amount22 });23 return next && next();24 }25 asimov.config('state', 'starting');26 self.runSequence('preinit').done(function () {27 self.runSequence('init').done(function () {28 self.runSequence('postinit').done(function () {29 asimov.config('state', 'running');30 self.publish('app:started');31 process.send && process.send({32 'event': 'app:started',33 'initializers': amount,34 'started': started.valueOf()35 });36 if (typeof next === 'function') next();37 }).fail(self.error);38 }).fail(self.error);39 }).fail(self.error);40 return self.publicInterface();41 },42 'onMessage': function (data) {43 var self = this;44 // console.log('worker received', data);45 },46 // more or less only here to catch the "exit" event47 'terminateWorker': function () {48 process.exit();49 },50 'shutdownWorker': function () {51 var self = this;52 if (!self._shutdown) {53 asimov.config('state', 'stopping');54 self._shutdown = true;55 process.connected && process.disconnect();56 var killSelf = setTimeout(function () {57 process.exit();58 }, 3 * 1000);59 killSelf.unref();60 self.runSequence('shutdown');61 }62 }...
luna.js
Source:luna.js
...52 setTimeout(function() {53 prevWorker.kill();54 }, 60000);55 workersKilled++;56 shutdownWorker();57 });58 newWorker.on("message", handleMsg);59 }60 shutdownWorker();61 };62} else {63 var backend = require("./backend");...
app.js
Source:app.js
...16 () => () => {}, // Empty graceful shutdown function17 ),18 ]),19 ([ shutdownManager, shutdownWorker ]) => async () => {20 await shutdownWorker()21 await shutdownManager()22 },23 shutdownFunction => setupProcessHandlers(logger, shutdownFunction),...
Using AI Code Generation
1Cypress.on('uncaught:exception', (err, runnable) => {2 if (err.message.includes('ResizeObserver loop limit exceeded')) {3 }4 })5 describe('My First Test', () => {6 it('Does not do much!', () => {7 expect(true).to.equal(true)8 })9 })10 Cypress.on('uncaught:exception', (err, runnable) => {11 if (err.message.includes('ResizeObserver loop limit exceeded')) {12 }13 })14 describe('My First Test', () => {15 it('Does not do much!', () => {16 expect(true).to.equal(true)17 })18 })19 Cypress.on('uncaught:exception', (err, runnable) => {20 if (err.message.includes('ResizeObserver loop limit exceeded')) {21 }22 })23 describe('My First Test', () => {24 it('Does not do much!', () => {25 expect(true).to.equal(true)26 })27 })28 Cypress.on('uncaught:exception', (err, runnable) => {29 if (err.message.includes('ResizeObserver loop limit exceeded')) {30 }31 })32 describe('My First Test', () => {33 it('Does not do much!', () => {34 expect(true).to.equal(true)35 })36 })37 Cypress.on('uncaught:exception', (err, runnable) => {38 if (err.message.includes('ResizeObserver loop limit exceeded')) {39 }40 })41 describe('My First Test', () => {42 it('Does not do much!', () => {43 expect(true).to.equal(true)44 })45 })46 Cypress.on('uncaught:exception', (err, runnable)
Using AI Code Generation
1Cypress.on('uncaught:exception', (err, runnable) => {2 })3 describe('My First Test', function() {4 it('Does not do much!', function() {5 cy.contains('type').click()6 cy.url().should('include', '/commands/actions')7 cy.get('.action-email')8 .type('fake@email')9 .should('have.value', 'fake@email')10 })11 })
Using AI Code Generation
1cy.shutdownWorker()2### `cy.shutdownWorkers()`3cy.shutdownWorkers()4### `cy.shutdownWorkers({ force: true })`5cy.shutdownWorkers({ force: true })6### `cy.shutdownWorkers({ force: false })`7cy.shutdownWorkers({ force: false })8### `cy.getWorker()`9cy.getWorker('worker-1')10### `cy.getAllWorkers()`11cy.getAllWorkers()12### `cy.getWorkerState()`13cy.getWorkerState('worker-1')14### `cy.getAllWorkersState()`15cy.getAllWorkersState()16### `cy.getWorkerMessage()`17cy.getWorkerMessage('worker-1')18### `cy.getAllWorkersMessage()`19cy.getAllWorkersMessage()20### `cy.getWorkerError()`21cy.getWorkerError('worker-1')22### `cy.getAllWorkersError()`23cy.getAllWorkersError()24### `cy.getWorkerOnMessage()`
Cypress check that a string does not exist in body, excluding a block or div
How to get div 'text' value in Cypress test using jquery
wait() cannot find previously triggered alias route
Why does cypress variable inside of it() stay as the last value assigned to that variable, whereas outside of it() it works correctly? (Example)
Cypress get URL as a string to use in next commands not working
Cypress.io cy.request() pass body as var
Re-run Cypress tests in GUI when webpack-dev-server causes page reload
Cypress and unstable DOM
Should e2e tests persist data in real databases?
Cypress with OpenLayers - how to simulate ctrl + mouse drag
The cy.get().not()
command is not seen very often, but the docs say
Opposite of .filter()
which kind of means *take all the elements found in get()
and filter out any that match the .not()
.
So in
cy.get('body')
.not('.footer') // no class footer on body, no effect
.should('not.contain', 'Miami') // fails because not.contain is recursive
body
does not have .footer
, so nothing is filtered out.
And the next step .should('not.contain'
searches all children of body
, which includes .footer
, and therefore fails the test.
If the footer is a direct child of body
, you can add a .children()
to make it work
<body>
<div>NYC</div>
<div class="footer">Miami</footer>
</body>
cy.get('body')
.children() // direct descendants only
.not('.footer') // now .footer is excluded
.should('not.contain', 'Miami') // passes
or using opposite logic
cy.get('body')
.find('.footer')
.siblings()
.should('not.contain', 'Miami')
If there is one or more levels between body and footer, you need to target the level correctly
<body>
<div class=""wrapper1">
<div class=""wrapper2">
<div>NYC</div>
<div class="footer">Miami</footer>
</div>
</div>
</body>
cy.get('body')
.children() // wrapper 1
.children() // wrapper 2
.children()
.not('.footer') // .footer is excluded
.should('not.contain', 'Miami') // passes
but this starts to look messy, and is fragile if the structure changes.
The basic problem is that .not()
is not recursive but .should('not.contain', 'Miami')
is recursive. What would work is a non-recursive text checker.
This is the most robust way I could come up with
cy.get('body')
.find('*') // children of body - recursive
.not('.footer') // exclude the footer
.each($el => {
cy.wrap($el.contents().get(0).textContent) // text of this element only (not children)
.should('not.contain', 'Miami') // passes
})
where
$el.contents() // list of element and all child nodes
.get(0) // filter just the parent
.textContent // get it's text
Check out the latest blogs from LambdaTest on this topic:
For web developers, there is no shortage of resources. Be it text editors, learning materials, build tools, deployment tools, testing tools, or any other category that can ease their lives as web developers!. However, if you are starting a new project, confusion may arise regarding the best-suited tool for your team.
“The future belongs to those who believe in the beauty of their dreams.”—Eleanor Roosevelt
We are nearing towards the end of 2019, where we are witnessing the introduction of more aligned JavaScript engines from major browser vendors. Which often strikes a major question in the back of our heads as web-developers or web-testers, and that is, whether cross browser testing is still relevant? If all the major browser would move towards a standardized process while configuring their JavaScript engines or browser engines then the chances of browser compatibility issues are bound to decrease right? But does that mean that we can simply ignore cross browser testing?
Selenium has always been the most preferred test automation framework for testing web applications. This open-source framework supports popular programming languages (e.g. Java, JavaScript, Python, C#, etc.), browsers, and operating systems. It can also be integrated with other test automation frameworks like JUnit, TestNG, PyTest, PyUnit, amongst others. As per the State of open source testing survey, Selenium is still the king for web automation testing, with 81% of organizations preferring it over other frameworks.
Black Friday and Cyber Monday are the most important days of the holiday shopping season. To prevent any unexpected surprises during the biggest shopping season of the year, retailers need to understand how their website and mobile applications will respond to a major and sudden surge of traffic. Any delays in loading pages and unexpected timeouts will result in frustrated shoppers abandoning their carts or shopping elsewhere.
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!!