Best JavaScript code snippet using cypress
ValueScopeNode.js
Source:ValueScopeNode.js
...56 }57 this.scannedLocal = true;58 }59 }60 get resolveOn() {61 return this._resolveOn;62 }63 get value() {64 return this._value;65 }66 // 본 ëª¨ìµ : ìì ì ë°ì´í°íì
ì ë§ì¶° ë°ì´í°ë¥¼ ë°ííë¤.67 get shapeValue() {68 // return this.value.variable;69 try {70 switch (this.dataType) {71 case DataTypes.String:72 return this.value.byString;73 case DataTypes.Number:74 return this.value.byNumber;75 case DataTypes.Boolean:76 return this.value.byBoolean;77 case DataTypes.Array:78 case DataTypes.Object:79 return this.value.byObject;80 }81 } catch (_e) {82 throw _e;83 }84 }85 get plainValue() {86 return this.value.variable;87 }88 get dataType() {89 return this._dataType;90 }91 set resolveOn(_onRes) {92 this._resolveOn = _onRes;93 }94 // ì¸ë¶ììë value setter 를 ì¬ì©íì§ ììì¼ íë¤.95 // value Nodeë MetaText ê°ì²´ì´ë¤.96 set value(_value) {97 this._value = _value;98 }99 set plainValue(_value) {100 this.value.variable = _value;101 }102 set dataType(_dataType) {103 this._dataType = _dataType;104 }105 // ì
ë ¥ë ë°ì´í°ë¥¼ ë°ì´í° íì
ì ë°ë¼ ë¶ë³íì¬ ìì ìê² ì ì¥íë¤....
sender.js
Source:sender.js
1const { DEFAULT_GAS_LIMIT, NOC_TIMEOUT_MINUTES } = require('../configs/env')2const helpers = require('./helpers')3const { web3 } = require('./web3-manager')4const log = require('@arbiter/dumb-lumberjack')()5const { redis } = require("./redis-manager")6const { decrypt } = require('./crypt')7const { getMasterAddress } = require("./address-manager")8const getNetworkType = require("./network-manager")9const WARN_TIMEOUT_MILLIS = NOC_TIMEOUT_MINUTES * 60 * 100010module.exports = {11 /*12 IMPORTANT13 This file manages ALL gas, gas price, and nonce concerns14 @parameters (15 opts: txObject like https://web3js.readthedocs.io/en/1.0/web3-eth.html#sendtransaction,16 resolveOn: receipt|txid|transactionHash|success17 sendable: the result of something like contract.methods.doAThing({ args })18 )19 */20 async signAndSend(opts, resolveOn, sendable) {21 opts = await this._normalizeTxOpts(opts)22 let network = await getNetworkType()23 let promivent24 log.debug(`all systems calibrated, preparing to fire`, opts)25 if ( network !== "private" ) {26 log.debug(`signing and sending`)27 let signed = await this._sign(opts)28 promivent = web3.eth.sendSignedTransaction(signed.rawTransaction)29 } else if ( network === "private" && sendable !== undefined ) {30 log.debug(`sending sendable`)31 promivent = sendable.send(opts)32 } else {33 let msg = `Unsure of how to sign and send with network: ${network}`34 log.error(msg, opts, sendable)35 throw Error(`Unknown signing condition`)36 }37 return new Promise((resolve, reject) => {38 // TODO: add on-chain checking39 let nocTimeout40 promivent.on('receipt', receipt => {41 log.info(`transaction receipt`, receipt)42 // save the result43 // TODO: calculate fees of the tx44 redis.set(45 `tx:${receipt.transactionHash.toLowerCase()}:receipt`,46 JSON.stringify(receipt)47 ).catch(ex => {48 log.error(`could not store receipt for txid ${receipt.transactionHash}`, ex)49 })50 // clear the NOC check51 clearTimeout(nocTimeout)52 if ( resolveOn === 'receipt' ) {53 resolve(receipt)54 }55 if ( resolveOn === 'success' ) {56 if ( helpers.isReceiptSuccessful(receipt) ) {57 resolve(receipt)58 } else {59 reject(new Error(`unsuccessful status ${receipt.status}`))60 }61 }62 }).on('transactionHash', hash => {63 log.info(`sent transaction`, hash)64 // store the params of the original tx65 redis.set(`tx:${hash.toLowerCase()}:params`, JSON.stringify(opts)).catch(ex => {66 log.error(`could not store tx params for txid ${hash}`, JSON.stringify(opts), ex)67 })68 nocTimeout = setTimeout(() => {69 log.alert(`${hash} is not on chain after ${NOC_TIMEOUT_MINUTES} minutes`, opts)70 }, WARN_TIMEOUT_MILLIS)71 if ( ['transactionHash','txid'].includes(resolveOn) ) {72 resolve(hash)73 }74 }).on('error', async err => {75 log.alert(`error sending transaction`, err.message)76 if ( err.message.includes("nonce too low") ) {77 // clear the nonce and try again78 try {79 await this._clearNonce(opts.from)80 // try it again81 this.signAndSend(opts, resolveOn, sendable).then(resolve).catch(reject)82 } catch (ex) {83 reject(ex)84 }85 } else {86 // TODO: handle nonce errors "Transaction nonce is too low"87 reject(err)88 }89 })90 })91 },92 async _clearNonce(account) {93 let key = `sending:next-nonce:${account}`94 return redis.del(key)95 },96 async _getNonce(account) {97 account = account.toLowerCase()98 let key = `sending:next-nonce:${account}`99 let nonce = await redis.incr(key)100 // if no nonce previously existed, double-check101 if ( nonce === 1 ) {102 let count = await web3.eth.getTransactionCount(account, 'pending')103 if ( count !== 0 ) {104 await redis.set(key, count+1)105 return count;106 }107 }108 return nonce - 1109 },110 async _sign(tx) {111 let isProd = ['prod', 'production'].includes(process.env['NODE_ENV'])112 let info = await redis.hgetall(tx.from.toLowerCase())113 log.debug(`signing address info`, info)114 if (isProd && (!info || !info.privKey)) {115 throw Error(`could not sign transaction with ${tx.from}, unknown address`)116 } else if (!info || !info.privKey) {117 log.warn(`pk not found redis, this will not be an option in production!! trying to sign from parity keystore`)118 let signed = await web3.eth.signTransaction(tx, tx.from)119 return signed.raw120 }121 log.debug(`signing with pk from redis for account`, tx.from)122 // otherwise, we have the pk in redis, sign it123 let decrypted = decrypt(info.privKey)124 let signedTx = await web3.eth.accounts.signTransaction(tx, '0x' + decrypted)125 log.debug(`signedTx`, signedTx)126 return signedTx127 },128 async _normalizeTxOpts(opts) {129 if ( !opts || ( !opts.data && !opts.to ) ) {130 log.warn(`don't know what to sign here`, opts)131 throw Error("will not sign empty transaction")132 }133 opts = opts || {}134 opts.gasPrice = await helpers.getGasPrice(opts)135 opts.from = opts.from || await getMasterAddress()136 opts.value = opts.value || '0'137 opts.gas = opts.gas || DEFAULT_GAS_LIMIT || 100000138 opts.nonce = await this._getNonce(opts.from)139 return opts140 }...
Server.js
Source:Server.js
...85 if(!self.tunnel)86 return Promise.reject('')87 return new Promise((resolve, reject) => {88 console.log(`pinging tunnel @ ${self.tunnel}`)89 self.server.resolveOn('ping', () => resolve(self.tunnel), reject, 10000)90 self.http.get(`http://${dstnt}?ping=1`, (res) => {91 if (res.statusCode !== 200) {92 console.error(`Got error pinging server @ http://${dstnt}?ping: ${res}`)93 reject(res) 94 }95 }).on('error', (e) => {96 console.error(`Got error pinging tunnel @ ${self.tunnel}: ${e.message}`)97 reject(e)98 })99 })100 }101 return new Promise((resolve, reject) => {102 ping()103 .then(resolve)104 .catch(() => {105 startTunnel()106 .then(registerRemote)107 .then(resolve)108 .catch(reject)109 })110 }) 111 }112 resolveOn(state, resolve, reject = () => {}, timeout = 0) {113 const self = this114 console.log(`waiting for ${state} state through tunnel @ ${self.tunnel}`)115 const timeoutID = setTimeout(() => reject(`request for ${state} through ${self.tunnel} timed out`), timeout)116 self.states[state] = (args) => {117 clearTimeout(timeoutID)118 resolve(args)119 }120 }121 parseGetRequest(req) {122 const data = {}123 if(req.url.includes('?'))124 req.url125 .split('?')[1]126 .split('&')...
transaction.js
Source:transaction.js
1import Base from './base'2import Contract from './contract'3import Network from './network'4import Utils from './utils'5export default class Transaction extends Base {6 constructor (args) {7 super(args)8 this.contract = new Contract(args)9 this.network = new Network(args)10 this.utils = new Utils(args)11 }12 send (from, to, amount, token, { resolveOn = 'hash' } = {}) {13 if (token.address === this.genesisAddress) {14 return this.sendEth(from, to, amount, { resolveOn })15 } else {16 return this.sendToken(from, to, amount, token, { resolveOn })17 }18 }19 sendEth (from, to, amount, { resolveOn = 'hash' } = {}) {20 const value = this.web3.utils.toWei(amount.toString(), 'ether')21 const promise = new Promise((resolve, reject) => {22 this.web3.eth.sendTransaction({ from, to, value })23 .on('transactionHash', hash => {24 console.log('Transaction Hash:', hash)25 if (resolveOn === 'hash') resolve(hash)26 })27 .on('receipt', receipt => {28 console.log('Receipt:', receipt)29 if (resolveOn === 'receipt') resolve(receipt)30 })31 .on('confirmation', (n, receipt) => {32 console.log(`Confirmation ${n}:`, receipt)33 })34 .on('error', error => {35 if (error.message.includes('User denied transaction signature')) {36 reject(new Error('Transaction rejected'))37 } else if (error.message.includes('gas too low')) {38 reject(new Error('Please add more gas'))39 } else {40 reject(new Error(error))41 }42 })43 })44 return promise45 }46 async sendToken (from, to, amount, token, { resolveOn = 'hash' } = {}) {47 const units = this.utils.unitsFromDecimals(token.decimals)48 const amountWei = this.web3.utils.toWei(amount.toString(), units)49 const tokenAbi = this.contract.abiFromStandard(token.standard)50 const contract = await this.contract.getInstance(tokenAbi, token.address)51 const gas = await contract.methods.transfer(to, amountWei).estimateGas({ from })52 const promise = new Promise((resolve, reject) => {53 contract.methods.transfer(to, amountWei).send({ from, gas })54 .on('transactionHash', hash => {55 console.log('Transaction Hash:', hash)56 if (resolveOn === 'hash') resolve(hash)57 })58 .on('receipt', receipt => {59 console.log('Receipt:', receipt)60 if (resolveOn === 'receipt') resolve(receipt)61 })62 .on('confirmation', (n, receipt) => {63 console.log(`Confirmation ${n}:`, receipt)64 })65 .on('error', error => {66 if (error.message.includes('User denied transaction signature')) {67 reject(new Error('Transaction rejected'))68 } else if (error.message.includes('gas too low')) {69 reject(new Error('Please add more gas'))70 } else {71 reject(new Error(error))72 }73 })74 })75 return promise76 }77 async walletConnectTxObject (from, to, amount, token) {78 const amountWei = this.web3.utils.toWei(amount.toString(), 'ether')79 const gasPrice = this.web3.utils.numberToHex((await this.network.gasPrice()))80 if (token.address === this.genesisAddress) {81 const value = this.web3.utils.numberToHex(amountWei)82 const data = '0x'83 const gas = this.web3.utils.numberToHex(21000)84 return { from, to, data, value, gas, gasPrice }85 } else {86 const value = '0x00'87 const tokenAbi = this.contract.abiFromStandard(token.standard)88 const contract = await this.contract.getInstance(tokenAbi, token.address)89 const gas = await contract.methods.transfer(to, amountWei).estimateGas({ from, gasPrice })90 const data = contract.methods.transfer(to, amountWei).encodeABI()91 to = token.address92 return { from, to, data, value, gas, gasPrice }93 }94 }...
worker.as.promise.js
Source:worker.as.promise.js
1import { v4 } from 'uuid';2import { PREFIX, SUCCESS, ERROR } from './consts';3const PENDINGS = {}; // pending promises4// dispatch to worker and wait for a particular response to resolve5export const middleware = () => (next) => (action) => {6 // if action is a worker one with a wait data7 if (action.type && action.type.startsWith(PREFIX)8 && action.resolvers) {9 let p = workerAsPromise(next, action);10 // save with infos11 // what if 2 with same datas? should had an uuid?12 PENDINGS[p.id] = p;13 // return promise14 return p.promise;15 }16 else {17 // check if type must resolve or reject a pending promise18 if (PENDINGS[action.workerID]) {19 // end dispatching action first.20 next(action);21 PENDINGS[action.workerID].doResolve(action);22 delete PENDINGS[action.workerID];23 return;24 }25 }26 return next(action);27};28let resolver = (resolve, reject, resolvers) => (action) => {29 let { type } = action;30 let { resolveOn, rejectOn } = resolvers;31 /* istanbul ignore else always set */32 if (resolveOn) {33 if (typeof resolveOn === 'string' && resolveOn === type) return resolve(action);34 else if (Array.isArray(resolveOn) && resolveOn.find((r) => r === type)) return resolve(action);35 }36 /* istanbul ignore else always set */37 if (rejectOn) {38 if (typeof rejectOn === 'string' && rejectOn === type) return reject(action);39 else if (Array.isArray(rejectOn) && rejectOn.find((r) => r === type)) return reject(action);40 }41}42function workerAsPromise(next, action) {43 let _resolve, _reject;44 let id = action.resolvers.workerID || v4();45 let resolveOn = action.resolvers.resolveOn || [action.type.replace(PREFIX, '') + SUCCESS,];46 let rejectOn = action.resolvers.rejectOn || [action.type.replace(PREFIX, '') + ERROR];47 let pr = new Promise((resolve, reject) => {48 _resolve = resolve;49 _reject = reject;50 // next action + payload51 // resolveOn && rejectOn, if not set, add default one52 next({53 ...action,54 workerID: id,55 resolvers: { resolveOn, rejectOn }56 });57 });58 return { doResolve: resolver(_resolve, _reject, { resolveOn, rejectOn }), promise: pr, id }...
get-files-changed.js
Source:get-files-changed.js
1const { EventEmitter } = require("events");2const { watchPath } = require("@atom/watcher");3const { isMatch } = require("micromatch");4const event = require("@await/event");5const eventEmitters = { };6module.exports = function filesChanged({ source, match })7{8 const eventEmitter = getEventEmitter(source);9 const test = toMatch(match);10 const canceled = Symbol();11 const resolveOn = ["files-changed", canceled];12 13 const cancel = () => eventEmitter.emit(canceled);14 const waiting = event({ eventEmitter, resolveOn })15 .then([_, events] => console.log(_));16 return Object.assign(waiting, { cancel });17/*18 return function ()19 {20 const await 21 }22 eventEmitter.on();23 const emit = events => events.length > 0 &&24 eventEmitter.emit("files-changed", events);25 const watcher = watchPath(source, { }, events =>26 emit(events.filter(event => matches(event.path))));27 const canceled = Symbol();28 const cancel = () => eventEmitter.emit(canceled);29 const resolveOn = ["files-changed", canceled];30 const filesChanged = event({ eventEmitter, resolveOn });31 return Object.assign(filesChanged, { cancel });*/32}33function getEventEmitter(source)34{35 if (eventEmitters[source])36 return eventEmitters[source].reference();37 const referenceCount = 0;38 const reference = () => (++referenceCount, eventEmitters);39 const dereference = () => --referenceCount;40 const eventEmitters = Object.assign(new EventEmitter(), dereference);41 const watcher = watchPath(source, { },42 events => emitter.emit("files-changed", events));43 eventEmitters[source] = { reference, watcher };44 return reference();45}46function toMatch(match)47{48 if (typeof match === "function")49 return match;50 if (typeof match === "string")51 return path => isMatch(path, match);52 if (typeof match === "undefined" || match === true)53 return () => true;54 throw TypeError("Bad type for match");...
index.js
Source:index.js
1const axios = require("axios");2const User = require("./lib/user");3const Module = require("./lib/module");4const Planning = require("./lib/planning");5const Grades = require("./lib/grades");6const Home = require("./lib/home");7const Projet = require("./lib/project");8const Activities = require("./lib/activities");9class IntranetApi {10 /**11 * Init the IntranetApi12 * @param {string} autologin - The autologin of the user13 */14 constructor(autologin) {15 this.autologin = autologin.replace("https://intra.epitech.eu/", "");16 this.url = `https://intra.epitech.eu/${this.autologin}`;17 this.login = null;18 this.city = null;19 this.year = null;20 this.user = new User(this);21 this.module = new Module(this);22 this.grades = new Grades(this);23 this.planning = new Planning(this);24 this.home = new Home(this);25 this.project = new Projet(this);26 this.activities = new Activities(this);27 }28 async get(endpoint, filter, resolveonError) {29 return new Promise((resolve, reject) => {30 axios31 .get(`${this.url}${endpoint}?format=json${filter}`)32 .then((response) => {33 resolve(response.data);34 })35 .catch((error) => {36 if (resolveonError) {37 resolve(error.response.data);38 } else {39 reject(error);40 }41 });42 });43 }44 async post(endpoint, data, resolveonError) {45 return new Promise((resolve, reject) => {46 axios47 .post(`${this.url}${endpoint}?format=json`, data)48 .then((response) => {49 resolve(response.data);50 })51 .catch((error) => {52 if (resolveonError) {53 resolve(error.response.data);54 } else {55 reject(error);56 }57 });58 });59 }60}...
pipe_events_to.js
Source:pipe_events_to.js
1'use strict'2const { Writable } = require('stream')3const arrayToStream = require('../lib/array_to_stream')4module.exports = async ({5 events,6 stream,7 listener,8 saga,9 projection,10 resolveOn = 'finish',11}) => {12 // listener, saga, projection are all synonymous13 if (!stream) stream = listener || saga || projection14 await new Promise((resolve, reject) => {15 const readableStream = arrayToStream(events)16 readableStream.pipe(stream).on('error', reject) //.on(resolveOn, resolve)17 readableStream18 .pipe(19 new Writable({20 objectMode: true,21 22 write: (_, __, cb) => cb(),23 })24 )25 .on(resolveOn, resolve)26 })...
Using AI Code Generation
1Cypress.Promise.resolveOn(Cypress, 'load:document').then(() => {2})3Cypress.on('load:document', () => {4})5Cypress.on('load:document', () => {6})
Using AI Code Generation
1Cypress.Promise.resolveOn(null, 1000).then(function(){2 console.log('resolved')3})4Cypress.Promise.rejectOn(null, 1000).then(function(){5 console.log('resolved')6}, function(){7 console.log('rejected')8})9Cypress.Promise.delay(1000).then(function(){10 console.log('resolved')11})12Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){13 console.log('resolved')14})15Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){16 console.log('resolved')17})18Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){19 console.log('resolved')20})21Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){22 console.log('resolved')23})24Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){25 console.log('resolved')26})27Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){28 console.log('resolved')29})30Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){31 console.log('resolved')32})33Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){34 console.log('resolved')35})36Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){37 console.log('resolved')38})39Cypress.Promise.all([Cypress.Promise.resolve(1), Cypress.Promise.resolve(2)]).then(function(){40 console.log('resolved')41})
Using AI Code Generation
1Cypress.Promise.resolveOn(cy, 2, 1000).then((value) => {2 console.log(value);3});4cy.wrap(2).resolveOn(1000).then((value) => {5 console.log(value);6});7cy.wrap(2).resolveOn(Cypress.Promise, 1000).then((value) => {8 console.log(value);9});10cy.wrap(2).resolveOn(Cypress.Promise, cy, 1000).then((value) => {11 console.log(value);12});13cy.wrap(2).resolveOn(Cypress.Promise, cy, 1000, 3).then((value) => {14 console.log(value);15});16cy.wrap(2).resolveOn(Cypress.Promise, cy, 1000, 3, 'error').then((value) => {17 console.log(value);18});19cy.wrap(2).resolveOn(Cypress.Promise, cy, 1000, 3, 'error', 10000).then((value) => {20 console.log(value);21});22cy.wrap(2).resolveOn(Cypress.Promise, cy, 1000, 3, 'error', 10000, 'message').then((value) => {23 console.log(value);24});25cy.wrap(2).resolveOn(Cypress.Promise, cy, 1000, 3, 'error', 10000, 'message', {a:1}).then((value) => {26 console.log(value);27});
Using AI Code Generation
1Cypress.Promise.resolveOn(Cypress, 'test:after:run', () => {2 console.log('test:after:run event fired');3});4Cypress.on('test:after:run', (attributes) => {5 console.log('test:after:run event fired');6});7Cypress.on('test:after:run', (attributes) => {8 console.log('test:after:run event fired');9});10Cypress.on('test:after:run', (attributes) => {11 console.log('test:after:run event fired');12});13Cypress.on('test:after:run', (attributes) => {14 console.log('test:after:run event fired');15});16Cypress.on('test:after:run', (attributes) => {17 console.log('test:after:run event fired');18});19Cypress.on('test:after:run', (attributes) => {20 console.log('test:after:run event fired');21});22Cypress.on('test:after:run', (attributes) => {23 console.log('test:after:run event fired');24});25Cypress.on('test:after:run', (attributes) => {26 console.log('test:after:run event fired');27});28Cypress.on('test:after:run', (attributes) => {29 console.log('test:after:run event fired');30});
Using AI Code Generation
1var resolvedPromise = false;2var promise = Cypress.Promise.resolve()3promise = promise.resolveOn(() => resolvedPromise)4.then((value) => {5 console.log(value);6});7cy.wait(5000);8resolvedPromise = true;9promise.then((value) => {10 console.log(value);11});12cy.wait(5000);13resolvedPromise = false;14promise.then((value) => {15 console.log(value);16});17cy.wait(5000);18resolvedPromise = true;19promise.then((value) => {20 console.log(value);21});22cy.wait(5000);23resolvedPromise = false;24promise.then((value) => {25 console.log(value);26});27cy.wait(5000);28resolvedPromise = true;29promise.then((value) => {30 console.log(value);31});32cy.wait(5000);33resolvedPromise = false;34promise.then((value) => {35 console.log(value);36});37cy.wait(5000);38resolvedPromise = true;39promise.then((value) => {40 console.log(value);41});42cy.wait(5000);43resolvedPromise = false;44promise.then((value) => {45 console.log(value);46});47cy.wait(5000);
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!!