Best JavaScript code snippet using cypress
xvfb.js
Source: xvfb.js
...175 console.error('stopped sync');176 xvfb.start(function(err) {177 assert.equal(err, null);178 console.error('started async');179 xvfb.stop(function(err) {180 assert.equal(err, null);181 console.error('stopped async');182 xvfb.start(function(err) {183 assert.equal(err, null);184 console.error('started async');185 xvfb.stopSync();186 console.error('stopped sync');187 xvfb.startSync();188 console.error('started sync');189 xvfb.stop(function(err) {190 assert.equal(err, null);191 console.error('stopped async');192 });193 });194 });195 });...
index.js
Source: index.js
...25 // console.log(newUrl);26 })27 .on('crashed', function(event, url){28 console.log('[Nightmare] crashed');29 xvfb.stop(function(err) {30 reject('crashed');31 }); 32 })33 .on('did-fail-load', function(event){34 console.log('[Nightmare] did-fail-load');35 console.log(event);36 // event.preventDefault();37 // reject('did-fail-load');38 })39 .on('new-window', function(event, url){40 console.log('new-window');41 event.preventDefault();42 })43 .goto(url)44 // .viewport(2000, 1000)45 .wait(2000)46 .evaluate(function(url) {47 // console.log(' ! - ! - ! - evaluate - ! - ! - !');48 var list, 49 result = [];50 if(url.search(/olx\.pl/i) != -1){51 // console.log(' - - - > olx');52 list = document.querySelectorAll('div.listHandler #offers_table>tbody>tr');53 if(!list)54 xvfb.stop(function(err) {55 reject('broken link');56 });57 58 for(var i=0; i<list.length; i++){59 var ad = list[i];60 if( !ad.querySelector('tr td div.space.rel p.marginbott5 span') ) continue;61 let id = ad.querySelector('table').getAttribute("data-id");62 let name = ad.querySelector('tr td div.space.rel h3 strong').innerText;63 let location = ad.querySelector('tr td div.space.rel p.marginbott5 span').innerText;64 let date = ad.querySelector('tr td div.space.rel p.x-normal').innerText;65 let price = ad.querySelector('tr td div.space.rel.inlblk p.price strong').innerText;66 let link = ad.querySelector('tr td div.space.rel a').getAttribute("href");67 let trade = ad.querySelector('tr td div.space.rel.inlblk span.normal.inlblk.pdingtop5');68 let pic = ad.querySelector('img');69 pic = pic ? pic.getAttribute("src") : "<no thumb photo>";70 if( id && name && location && date && price && pic && link){71 if(trade) trade = true; 72 else trade = false;73 result.push({74 id: id,75 name: name,76 location: location,77 date: date,78 price: price,79 pic: pic,80 link: link,81 trade: trade82 });83 }else reject('broken evaluate html parsing');84 }85 }86 else{ 87 xvfb.stop(function(err) {88 reject('wrong link');89 }); 90 }91 if(!result) 92 xvfb.stop(function(err) {93 reject('empty result array');94 });95 96 return result;97 }, url)98 .end()99 .then(function(results) {100 console.log(" - donor html list - ");101 console.log(results);102 xvfb.stop(function(err) {103 resolve(results);104 });105 })106 .catch(err => {107 console.log(" { Nightmare REJECT } ");108 console.error(err);109 xvfb.stop(function(err) {110 reject(err);111 });112 113 })114}); // xvfb115 });116 } catch (e) {117 console.log(e);118 return 0;119 }...
typeProfilingWorker.test.js
Source: typeProfilingWorker.test.js
1const fs = require( 'fs' );2const assert = require( 'assert' );3const runnerClass = require( `../src/typeProfilingRunner` );4const HTTPServer = require( 'http-server' );5const config = require( 'rc' )( 'tasks' );6const Xvfb = require( '@cypress/xvfb' );7const Promise = require( 'bluebird' );8const xvfb = Promise.promisifyAll(9 new Xvfb( {10 xvfb_args: '-screen 0 1024x768x24 -ac -nolisten tcp -dpi 96 +extension GLX +extension RENDER +extension RANDR'.split( / /g ),11 timeout: 1000012 } )13);14const retryStop = ( i = 0 ) => {15 return xvfb.stopAsync().catch( { timedOut: true }, ( e ) => {16 console.log( 'Timed out stopping', e.message );17 if ( i < 5 ) {18 return retryStop( i + 1 );19 }20 throw e;21 } );22};23const testBasePath = `${__dirname}/data/typeProfilingWorker/`;24const gold = JSON.parse( fs.readFileSync( `${__dirname}/data/typeProfilingWorker/gold.json`, 'utf8' ) );25describe( `typeProfilingWorker`, function () {26 let server;27 before( 'start xvfb', async function () {28 return await xvfb.startAsync();29 } );30 before( 'start server', function () {31 // start dev server32 server = HTTPServer.createServer( { cache: - 1, root: testBasePath } );33 server.listen( config.typesearch.baseUrl.port, config.typesearch.baseUrl.host );34 // always kill server on exit (too much maaaybe)35 [ 'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',36 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'37 ].forEach( signal => {38 process.on( signal, async () => {39 try {40 server.close();41 await retryStop();42 await xvfb.stopAsync();43 } catch ( err ) {44 console.error( `Server closing failed: ${err}` );45 }46 // process.exit( 1 );47 } );48 } );49 } );50 after( 'kill server', function () {51 server.close();52 } );53 after( 'kill xvfb', async function () {54 await retryStop();55 return await xvfb.stopAsync();56 } );57 after( 'clean up', function () {58 fs.unlinkSync( `${__dirname}/data/typeProfilingWorker/examples_css3d_sprites.json` );59 } );60 it( 'basics', async function () {61 // timeout due to the additional workload62 this.timeout( 240000 );63 // analyze64 const profiler = new runnerClass(65 testBasePath,66 testBasePath,67 'build/three.module.js',68 `http://${config.typesearch.baseUrl.host}:${config.typesearch.baseUrl.port}/`69 );70 profiler.loadUrls( [ `http://${config.typesearch.baseUrl.host}:${config.typesearch.baseUrl.port}/examples/css3d_sprites.html` ] );71 await profiler.run();72 // hacky73 const profile = JSON.parse( fs.readFileSync( `${__dirname}/data/typeProfilingWorker/examples_css3d_sprites.json`, 'utf8' ) );74 // even hackier75 gold.results.result.sort( ( scriptA, scriptB ) => scriptA.url.localeCompare( scriptB.url ) );76 gold.results.result.forEach( script => script.entries.sort( ( a, b ) => a.offset - b.offset ) );77 profile.results.result.sort( ( scriptA, scriptB ) => scriptA.url.localeCompare( scriptB.url ) );78 profile.results.result.forEach( script => script.entries.sort( ( a, b ) => a.offset - b.offset ) );79 assert.deepStrictEqual( profile, gold );80 } );...
app.js
Source: app.js
...77 })78 .then((r) => {79 console.log("r");80 console.log(r);81 // xvfb.stop();82 return {83 status: 200,84 body: r,85 };86 })87 .catch((e) => {88 console.log("error");89 console.log(e);90 // xvfb.stop();91 return {92 status: 500,93 body: e,94 };95 });...
HrefScraper.js
Source: HrefScraper.js
1const Nightmare = require('nightmare')2const Xvfb = require('xvfb')3const logger = require('./logger')4const os = require('os')5const BT_LINK = "http://www.bundestag.de" // https is NOT supported6const BT_LINK_OPENDATA = 'https://www.bundestag.de/services/opendata'7const runsOnWindows = (os.platform() === 'win32')8const useXvfb = !runsOnWindows && !process.argv.includes("noXvfb")9class DataScraper {10 _checkDocumentLink(href) {11 // get href; ex: 12 // (X) /blob/490380/1d83b7e383f9f09d88bd9e89aba07fb0/pp14-data.zip 13 // (O) /blob/562990/056c28051cb695642cb9d72521bba93b/19044-data.xml14 // check with regex:15 // \/blob\/.+?\/.+?\/(\d+)-data.(.*)16 // filename: <1. capturing group>-data.<2nd capturing group>17 const regex = /\/blob\/.+?\/.+?\/(\d+)-data.(.*)/18 const match = regex.exec(href)19 // check if 2nd capturing group is "xml"20 if(match && match[2] && match[2].toLowerCase() === 'xml'){21 // construct download link22 // result has to look like this: https://www.bundestag.de/blob/563398/99a2c9d4df10fcf44e67d084bf6c8f21/19046-data.xml23 return href24 }25 return undefined26 }27 async scrape() {28 let checkDocumentLink = this._checkDocumentLink29 let xvfb = undefined30 31 if(useXvfb){32 logger.info("Using Xvfb for scraping.")33 xvfb = new Xvfb()34 try {35 logger.info("Xvfb start sync.")36 xvfb.startSync()37 logger.info("Xvfb synced.")38 } catch (e) {39 logger.error(e)40 }41 }42 43 let nightmare = new Nightmare({ show: false })44 // we request nightmare to browse to the bundestag.de url and extract the whole inner html45 let hrefs = []46 await nightmare47 .goto(BT_LINK_OPENDATA)48 .wait(3000)49 .evaluate(() => Array.from(document.querySelectorAll('.bt-link-dokument')).map(a => a.href)) // return of document.querySelectorAll is not serializable.50 .end()51 .then(foundHrefs => {52 foundHrefs.forEach(href => {53 let candidate = checkDocumentLink(href)54 if(candidate){55 hrefs.push(candidate)56 }57 })58 logger.info("[scraper] found " + hrefs.length + " valid links out of " + foundHrefs.length + " links in total.")59 if(useXvfb && xvfb){60 xvfb.stopSync()61 }62 })63 .catch(err => {64 if(useXvfb && xvfb){65 xvfb.stopSync(); 66 }67 logger.error("[scraper] did not download any files.")68 logger.error(err)69 })70 return hrefs71 }72}...
test.js
Source: test.js
...6// const Xvfb = require('xvfb');7// xvfb = new Xvfb();8// xvfb.startSync();9// xvfb.stopSync();10// xvfb.stop(function(err) {});11const db = require('./db');12const scraper = require('./scraper');13const bot = require('./bot');14function notifyAll (item){15 db.getCollection('users', (collection) => {16 collection.find().toArray((err, users) => {17 console.log("users");18 console.log(users);19 for (var j = 0; j < users.length; j++) {20 bot.sendPhoto(users[j].telID, item.pic);21 bot.sendMessage(users[j].telID, `22 ${ item.link }23 ${ item.name }24 ${ item.location }...
fetchArtistData.js
Source: fetchArtistData.js
1const Nightmare = require('nightmare');2const zaq = require('zaq').as('fetchArtistData');3const Xvfb = require('xvfb');4const USE_XVFB = process.platform === 'linux';5module.exports = function fetchArtistData (artistId) {6 zaq.info('Fetching artist data...');7 return new Promise((resolve, reject) => {8 if (!artistId) {9 throw new TypeError('scrapeArtistDates: invalid artistId given');10 }11 const nightmare = Nightmare();12 const xvfb = USE_XVFB ? new Xvfb() : null;13 const artistProfileUrl = `https://www.bandsintown.com/a/${artistId}`;14 zaq.info(`Navigating to ${artistProfileUrl}...`);15 if (USE_XVFB) xvfb.startSync();16 nightmare17 .goto(artistProfileUrl)18 .wait('script[type="application/ld+json"]')19 .wait(2000)20 .evaluate(() => {21 var output = [];22 var json = document.querySelectorAll('script[type="application/ld+json"]');23 var documentCount = Object.values(json).length;24 json.forEach((rawDocument, index) => {25 var documentContent = rawDocument.innerHTML;26 var parsedContent = JSON.parse(documentContent);27 output.push(parsedContent);28 });29 return output;30 })31 .end()32 .then(data => (USE_XVFB ? xvfb.stopSync() : null) || data)33 .then(resolve)34 .catch(err => {35 reject(err);36 if (USE_XVFB) xvfb.stopSync();37 });38 });...
headless.js
Source: headless.js
1'use strict'2const command = process.argv.slice(2).join(' ')3if(!command.length)4 throw new Error('No command specified')5const execSync = require('child_process').execSync6const xvfb = new (require('xvfb'))({silent: true, timeout: 1000})7try {8 xvfb.startSync()9}10catch(err) {11 console.warn(err)12 xvfb.stopSync()13}14try {15 execSync(command, {stdio: 'inherit'})16}17finally {18 xvfb.stopSync()...
Using AI Code Generation
1var Xvfb = require('xvfb');2var xvfb = new Xvfb();3xvfb.start(function (err, xvfbProcess) {4 if (err) {5 console.log(err);6 }7 console.log('Xvfb process started on display ' + xvfbProcess._displayNum);8 console.log('Xvfb process PID: ' + xvfbProcess._pid);9 xvfb.stop(function (err) {10 if (err) {11 console.log(err);12 }13 console.log('Xvfb process stopped');14 });15});16"scripts": {17}18var Xvfb = require('xvfb');19var xvfb = new Xvfb();20xvfb.startSync();21console.log('Xvfb process started on display ' + xvfb._displayNum);22console.log('Xvfb process PID: ' + xvfb._pid);23xvfb.stopSync();24console.log('Xvfb process stopped');25"scripts": {26}27var Xvfb = require('xvfb');28var xvfb = new Xvfb({29});30xvfb.startSync();31console.log('Xvfb process started on display ' + xvfb._displayNum);32console.log('Xvfb process PID: ' + xvfb._pid);33xvfb.stopSync();34console.log('Xvfb process stopped');35"scripts": {36}37var Xvfb = require('xvfb');38var xvfb = new Xvfb({39});40xvfb.start(function (err, xvfbProcess) {41 if (err) {42 console.log(err);43 }44 console.log('Xvfb process started
Using AI Code Generation
1var xvfb = require('cypress-xvfb');2xvfb.stop();3var xvfb = require('cypress-xvfb');4xvfb.start();5var xvfb = require('cypress-xvfb');6xvfb.stop();7var xvfb = require('cypress-xvfb');8xvfb.start();9var xvfb = require('cypress-xvfb');10xvfb.stop();11var xvfb = require('cypress-xvfb');12xvfb.start();13var xvfb = require('cypress-xvfb');14xvfb.stop();15var xvfb = require('cypress-xvfb');16xvfb.start();17var xvfb = require('cypress-xvfb');18xvfb.stop();19var xvfb = require('cypress-xvfb');20xvfb.start();21var xvfb = require('cypress-xvfb');22xvfb.stop();23var xvfb = require('cypress-xvfb');24xvfb.start();25var xvfb = require('cypress-xvfb');26xvfb.stop();27var xvfb = require('cypress-xvfb');
Using AI Code Generation
1const cypressXvfb = require('cypress-xvfb');2const xvfb = new cypressXvfb({3});4xvfb.start((err, xvfbProcess) => {5 if (err) {6 throw err;7 }
Using AI Code Generation
1const Xvfb = require('xvfb');2const xvfb = new Xvfb();3xvfb.startSync();4xvfb.stopSync();5{6"env": {7}8}9{10"scripts": {11},12"devDependencies": {13}14}
Using AI Code Generation
1xvfb.stop((err) => {2 if (err) {3 return console.error(err);4 }5 console.log('Xvfb stopped');6});
Using AI Code Generation
1const cypress = require('cypress');2const xvfb = require('xvfb');3const start = async () => {4 const server = await xvfb.start();5 console.log('Xvfb server started on display ' + server.display);6 const results = await cypress.run();7 console.log(results);8 await xvfb.stop(server);9 console.log('Xvfb server stopped');10};11start();
Cypress does not always executes click on element
How to get current date using cy.clock()
.type() method in cypress when string is empty
Cypress route function not detecting the network request
How to pass files name in array and then iterating for the file upload functionality in cypress
confused with cy.log in cypress
why is drag drop not working as per expectation in cypress.io?
Failing wait for request in Cypress
How to Populate Input Text Field with Javascript
Is there a reliable way to have Cypress exit as soon as a test fails?
2022 here and tested with cypress version: "6.x.x"
until "10.x.x"
You could use { force: true }
like:
cy.get("YOUR_SELECTOR").click({ force: true });
but this might not solve it ! The problem might be more complex, that's why check below
My solution:
cy.get("YOUR_SELECTOR").trigger("click");
Explanation:
In my case, I needed to watch a bit deeper what's going on. I started by pin the click
action like this:
Then watch the console, and you should see something like:
Now click on line Mouse Events
, it should display a table:
So basically, when Cypress executes the click
function, it triggers all those events but somehow my component behave the way that it is detached the moment where click event
is triggered.
So I just simplified the click by doing:
cy.get("YOUR_SELECTOR").trigger("click");
And it worked ????
Hope this will fix your issue or at least help you debug and understand what's wrong.
Check out the latest blogs from LambdaTest on this topic:
When it comes to web automation testing, the first automation testing framework that comes to mind undoubtedly has to be the Selenium framework. Selenium automation testing has picked up a significant pace since the creation of the framework way back in 2004.
We just raised $45 million in a venture round led by Premji Invest with participation from existing investors. Here’s what we intend to do with the money.
Find element by Text in Selenium is used to locate a web element using its text attribute. The text value is used mostly when the basic element identification properties such as ID or Class are dynamic in nature, making it hard to locate the web element.
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?
Web products of top-notch quality can only be realized when the emphasis is laid on every aspect of the product. This is where web automation testing plays a major role in testing the features of the product inside-out. A majority of the web testing community (including myself) have been using the Selenium test automation framework for realizing different forms of web testing (e.g., cross browser testing, functional testing, etc.).
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!!