Best JavaScript code snippet using cypress
site.action.js
Source:site.action.js
...54 console.log('get js ok, js=' + js);55 jsFilePath = workingPath + "/do.js";56 fs.write(jsFilePath, js, 'w');57 console.log('get js ok, jsFilePath=' + jsFilePath);58 checkExit();59 } catch (e) {60 console.log('get js error, exit ... ...');61 phantom.exit();62 }63 }64 });65}66var getTask = function () {67 var server = host + "/data/t/get.php?token=winwaker";68 console.log('get task, ... ... ' + server);69 var page = require('webpage').create();70 page.open(server, function (status) {71 if (status !== 'success') {72 console.log('get task error, waiting ... ...');73 checkExit();74 } else {75 try {76 var json = page.plainText;77 console.log('get task ok, json=' + json);78 var taskResponse = JSON.parse(json);79 if (taskResponse.errorCode === "OK") {80 var task = taskResponse.task;81 console.log('get task ok, task.id=' + task.id);82 fetchTask(task);83 } else {84 console.log('get task error, erroCode=' + taskResponse.errorCode);85 checkExit();86 }87 } catch (e) {88 console.log('get task error, ex=' + e);89 checkExit();90 }91 }92 });93}94var fetchTask = function (task) {95 console.log('task.url=' + task.url);96 console.log('task.delay=' + task.delay);97 console.log('task.actions=' + task.actions.length);98 console.log('retry=' + retry);99 console.log('fetch task, ... ...');100 var delay = task.delay;101 if (delay <= 5) {102 delay = 5;103 }104 var settings = {105 operation: "GET",106 headers: {107 "userAgent": userAgent,108 },109 resourceTimeout: 10000, // 10 seconds110 javascriptEnabled: true,111 loadImages: true,112 localToRemoteUrlAccessEnabled: true,113 }114 var page = require('webpage').create();115 page.viewportSize = { width: 1200, height: 800 };116 page.open(task.url, settings, function (status) {117 if (status !== 'success') {118 retry--;119 if (retry > 0) {120 console.log('fetch error, retry ' + retry + ' ... ...');121 window.setTimeout(function () {122 fetchTask(task);123 }, 3000);124 } else {125 console.log('retry exceeded, exit !!!');126 checkExit();127 }128 } else {129 console.log('fetch ok !!!');130 console.log('load js, ... ...' + jsFilePath);131 if (page.injectJs(jsFilePath)) {132 console.log('load js ok !!!');133 var pos = 0;134 var intervalHandle = window.setInterval(function () {135 console.log('delay=' + delay);136 delay--;137 if (delay > 0) {138 pos += 400;139 console.log('scroll pos=' + pos);140 page.scrollPosition = { top: pos, left: 0 };141 } else {142 window.clearInterval(intervalHandle);143 var title = page.evaluate(function () {144 return document.title;145 });146 console.log("page title=" + title);147 console.log("page url=" + page.url);148 page.scrollPosition = { top: 0, left: 0 };149 // continue next150 var content = page.content;151 console.log("page content.length=" + content.length);152 // checkExit();153 actionTask(task, page);154 }155 }, 1000);156 } else {157 console.log('load js error, exit !!!');158 checkExit();159 }160 }161 });162}163var actionTask = function (task, page) {164 if (task.actions == null || task.actions.length == 0) {165 checkExit();166 } else {167 var action = task.actions[0];168 task.actions.splice(0, 1);169 var key = action.key;170 // delay, js171 if (action.key == 'delay') {172 var delay = parseInt(action.value, 10);173 console.log("action => delay " + delay);174 window.setTimeout(function () {175 actionTask(task, page);176 }, delay * 1000);177 } else if (action.key == "js") {178 var script = action.value;179 console.log("action => js " + script);180 page.evaluateJavaScript(script);181 actionTask(task, page);182 } else {183 checkExit();184 }185 }186}187var checkExit = function () {188 runCount--;189 exitCount = 0;190 console.log("###################### check exit, runCount=" + runCount);191 if (runCount <= 0) {192 phantom.exit();193 } else {194 window.setTimeout(function () {195 getTask();196 }, interDelay);197 }...
user.js
Source:user.js
1const { resolve } = require('path');2const USER_COLL= require('../database/user');3const ObjectID = require('mongoose').Types.ObjectId;45const { hash, compare} = require('bcrypt');6const { sign, verify } = require('../utils/jwt');7const { profile } = require('console');89/*10 INSERT NEW INFOMATION USER TO DATABASE 11*/12module.exports = class user extends USER_COLL{13 static insertNewUserToDatabase({ name, username,password, email}){14 return new Promise( async resolve =>{15 try {16 let checkExit = await USER_COLL.findOne({ username });17 if( checkExit ) 18 {19 return resolve({ error : true, message : 'exist'});20 }21 let hassPass = await hash( password , 8);22 let newUser = new USER_COLL({ name, username, password : hassPass, email })23 let infoUserAfterInsert = await newUser.save();24 if( !infoUserAfterInsert ) 25 {26 return resolve({ error : true, message : 'can not insert' });27 }28 return resolve({ error : false , data : infoUserAfterInsert});29 } catch ( error ) {30 return resolve({ error : true, message : error.message})31 }32 })33 }3435/*36 INSERT NEW INFOMATION USER TO DATABASE 37*/3839 static singIn({ username, password }) {40 return new Promise(async resolve =>{41 try {42 let checkExit = await USER_COLL.findOne({ username });4344 if( !checkExit ) return resolve({ error : true, message : 'UserName not exist'});4546 let passWord = checkExit.password;4748 let checkpass = await compare( password, passWord);49 if( !checkpass ) 50 {51 return resolve({ error: true , message: 'wrong pass'});52 }53 54 //tao token 55 await delete checkExit.password;56 57 let token = await sign( { data:checkExit } );58 59 return resolve( { error : false , data:{checkExit, token} } );60 } catch ( error ) {61 return resolve({ error: true, message: error.message} )62 }63 })64 }6566/*67 GET LIST INFORMATION USER FROM DATABASE IN TABLE USER68*/69 static getList(){70 return new Promise(async resolve =>{71 try {72 let listUser = await USER_COLL.find();73 if( !listUser ) 74 {75 return resolve({ error : true, message : "List not Exist"});76 }77 return resolve({ error : false, data : listUser})78 } catch ( error ) {79 return resolve({ error : true, message : error.message})80 }81 })82 }83 /*84 GET ONE OBJECT INFOMATION USER IN DATABASE85*/86 static getID( id )87 {88 return new Promise(async resolve =>{89 try {90 let inforUser = await USER_COLL.findById({ _id : id });91 if( !inforUser ) return resolve({erro : true , message : 'can not find'});92 return resolve({ error : true, data : inforUser})93 } catch ( error ) {94 return resolve({error : true, message : error.message})95 }96 })97}98 /*99 UPDATE INFORMATION USER TO DATABASES100*/101102static update({ id, name, phone, email, sex }) {103 return new Promise(async resolve => {104 try {105 106 if( !ObjectID.isValid( id )){107 return resolve({ error : true , message : 'params_invalid' });108 }109 let listUser = await USER_COLL.findByIdAndUpdate( id, {110 name, phone, email, sex111 }112 ,{113 new: true114 });115 116 if(!listUser){117 return resolve({error: true, message:'cannot_update_list'});118 }119 return resolve({error: false, message:'update_data_success', data: listUser});120121122 } catch (error) {123 return resolve({ error: true, message: error.message });124 }125 })126}127128 /*129 REMOVE ONE INFOMATION USER IN DATABASE OF TABLE USER 130*/131static remove( id )132 {133 return new Promise(async resolve =>{134 let checkExit = await USER_COLL.findById({_id:id});135 if(!checkExit)136 return resolve({error: true, message:'id not exist'});137 let removeUser= await USER_COLL.findByIdAndDelete(id);138 139 })140 }141
...
checkExit.test.js
Source:checkExit.test.js
...18};19describe('checkExit', () => {20 test('wrong type', () => {21 const tx = Tx.transfer([], []);22 expect(() => checkExit({}, tx)).toThrow('Exit tx expected');23 });24 test('successful tx', () => {25 const deposit = Tx.deposit(12, 500, ADDR_1, 0);26 const outpoint = new Outpoint(deposit.hash(), 0);27 const state = {28 unspent: {29 [outpoint.hex()]: deposit.outputs[0].toJSON(),30 },31 };32 const bridgeState = makeExitMock(ADDR_1, '500', 0, outpoint);33 const exit = Tx.exit(new Input(outpoint));34 checkExit(state, exit, bridgeState);35 expect(bridgeState.exitingUtxos).toEqual({});36 });37 test('not 1 input', () => {38 const deposit = Tx.deposit(12, 500, ADDR_1, 0);39 const outpoint = new Outpoint(deposit.hash(), 0);40 const state = {41 unspent: {42 [outpoint.hex()]: deposit.outputs[0].toJSON(),43 },44 };45 const exit = Tx.exit(new Input(outpoint));46 exit.inputs.push(new Input(outpoint));47 expect(() =>48 checkExit(state, exit, makeExitMock(ADDR_1, '500', 0))49 ).toThrow('Exit tx should have one input');50 });51 test('non-existent exit', () => {52 const deposit = Tx.deposit(12, 500, ADDR_1, 0);53 const outpoint = new Outpoint(deposit.hash(), 0);54 const state = {55 unspent: {56 [outpoint.hex()]: deposit.outputs[0].toJSON(),57 },58 };59 const exit = Tx.exit(new Input(outpoint));60 expect(() => {61 checkExit(state, exit, { exits: {} });62 }).toThrow('Trying to submit incorrect exit');63 });64 test('non-existent utxo', () => {65 const deposit = Tx.deposit(12, 500, ADDR_1, 0);66 const outpoint = new Outpoint(deposit.hash(), 0);67 const state = {68 unspent: {},69 };70 const exit = Tx.exit(new Input(outpoint));71 expect(() => {72 checkExit(state, exit, makeExitMock(ADDR_1, '500', 0));73 }).toThrow('Trying to submit incorrect exit');74 });75 test('wrong amount: erc20', () => {76 const deposit = Tx.deposit(12, 500, ADDR_1, 0);77 const outpoint = new Outpoint(deposit.hash(), 0);78 const state = {79 unspent: {80 [outpoint.hex()]: deposit.outputs[0].toJSON(),81 },82 };83 const exit = Tx.exit(new Input(outpoint));84 expect(() => {85 checkExit(state, exit, makeExitMock(ADDR_1, '600', 0));86 }).toThrow('Trying to submit incorrect exit');87 });88 test('wrong amount: erc721', () => {89 const color = 32769 + 1;90 const deposit = Tx.deposit(12, '500', ADDR_1, color);91 const outpoint = new Outpoint(deposit.hash(), 0);92 const state = {93 unspent: {94 [outpoint.hex()]: deposit.outputs[0].toJSON(),95 },96 };97 const exit = Tx.exit(new Input(outpoint));98 expect(() => {99 checkExit(state, exit, makeExitMock(ADDR_1, '600', color));100 }).toThrow('Trying to submit incorrect exit');101 });102 test('wrong color', () => {103 const deposit = Tx.deposit(12, 500, ADDR_1, 0);104 const outpoint = new Outpoint(deposit.hash(), 0);105 const state = {106 unspent: {107 [outpoint.hex()]: deposit.outputs[0].toJSON(),108 },109 };110 const exit = Tx.exit(new Input(outpoint));111 expect(() => {112 checkExit(state, exit, makeExitMock(ADDR_1, '500', 1));113 }).toThrow('Trying to submit incorrect exit');114 });...
users.js
Source:users.js
1const Router = require('koa-router')2const jwt = require('koa-jwt')3const router = new Router({ prefix: '/users' })4const { find, del, create, updated,5 findById, login, checkOwner, listFollowing,6 listFollowers, checkUserExit, follow, unfollow,7 followTopic, unfollowTopic, listFollowTopics,8 listDisLikingAnswers, listLikingAnswers,9 likeAnswer, unlikeAnswer, disLikeAnswer, unDisLikeAnswer,10 collectAnswer, unCollectAnswer, listCollectionAnswers11} = require('../controllers/users')12const { checkExit } = require('../controllers/topics')13const { checkAnswerExit } = require('../controllers/answers')14const { secret } = require('../config')15//å®ä¹è®¤è¯ä¸é´ä»¶16const auth = jwt({ secret })17// const auth = (async (ctx, next) => {18// const { authorization = '' } = ctx.request.header // èµåå§å¼åçè·¯å¤ç19// const token = authorization.replace('Bearer ', '')20// try {21// const user = jwt.verify(token, secret)22// ctx.state.user = user // åå¨ç¨æ·ä¿¡æ¯23// } catch (error) {24// ctx.throw(401, error.message)25// }26// await next()27// })28router.get('/', find)29router.get('/:id', findById)30router.post('/', create)31router.delete('/:id', auth, checkOwner, del)32router.patch('/:id', auth, checkOwner, updated)33router.post('/login', login)34router.get('/:id/following', checkUserExit, listFollowing)35router.get('/:id/followers', checkUserExit, listFollowers)36router.put('/following/:id', auth, checkUserExit, follow)37router.delete('/following/:id', auth, checkUserExit, unfollow)38// å
³æ³¨åæ¶å
³æ³¨è¯é¢39router.put('/followTopic/:id', auth, checkExit, followTopic)40router.delete('/followTopic/:id', auth, checkExit, unfollowTopic)41//ç¨æ·å
³æ³¨è¯é¢å表42router.get('/:id/followTopic', checkExit, listFollowTopics)43// ç¹èµ 模å44router.get('/:id/likeAnswers', checkUserExit, listLikingAnswers)45router.put('/likeAnswers/:id', auth, checkUserExit, likeAnswer, unDisLikeAnswer)46router.delete('/likeAnswers/:id', auth, checkUserExit, unlikeAnswer)47// 踩 模å48router.put('/dislikeAnswers/:id', auth, checkUserExit, disLikeAnswer, unlikeAnswer)49router.delete('/dislikeAnswers/:id', auth, checkUserExit, unDisLikeAnswer)50// æ¶èçæ¡æ¨¡å51router.get('/:id/collectingAnswers', checkUserExit, listCollectionAnswers)52router.put('/collectingAnswers/:id', auth, checkUserExit, collectAnswer)53router.delete('/collectingAnswers/:id', auth, checkUserExit, unCollectAnswer)...
lib.js
Source:lib.js
1importPackage(org.mechio.client.basic);2importPackage(org.mechio.api.motion);3importPackage(org.jflux.api.common.rk.position);4//importPackage(org.jflux.api.common.rk.utils);5function checkExit() {6 var b = controlSystem.isExitingNow();7 if(controlSystem.isExitingNow()) {8 throw new Error('now exiting...');9 }10}11function SRobot(robot) {12 checkExit();13 var myRobot = robot;14 this.move = function(positions, lenMillisec) {15 checkExit();16 myRobot.move(positions, lenMillisec);17 }18 this.getRobotId = function() {19 checkExit();20 return myRobot.getRobotId();21 }22}23function SAnimPlayer(animPlayer) {24 checkExit();25 var myAnimPlayer = animPlayer;26 this.playAnimation = function(animation) {27 checkExit();28 return myAnimPlayer.playAnimation(animation);29 }30 this.loopAnimation = function(animation) {31 checkExit();32 return myAnimPlayer.loopAnimation(animation);33 }34 this.stopAnimation = function(animation) {35 myAnimPlayer.stopAnimation(animation);36 checkExit();37 }38}39function connectRobot(ipAddress) {40 checkExit();41 if(ipAddress === undefined) {42 return new SRobot(MechIO.connectRobot());43 } else {44 return new SRobot(MechIO.connectRobot(ipAddress));45 }46}47function connectAnimationPlayer(ipAddress) {48 checkExit();49 if(ipAddress === undefined) {50 return new SAnimPlayer(MechIO.connectAnimationPlayer());51 } else {52 return new SAnimPlayer(MechIO.connectAnimationPlayer(ipAddress));53 }...
test-child-process-fork-and-spawn.js
Source:test-child-process-fork-and-spawn.js
...18default:19 assert(0);20}21var seenExit = false;22function checkExit(statusCode) {23 seenExit = true;24 assert.equal(statusCode, 0);25 process.nextTick(process.exit);26}27function haveExit() {28 assert.equal(seenExit, true);...
index.js
Source:index.js
...3require('make-promises-safe');4const Installer = require('./Installer');5(async () => {6 const installer = new Installer();7 await checkExit(installer.init());8 await checkExit(installer.installDeps());9 await checkExit(installer.findEmscripten());10 await checkExit(installer.findMSBuild());11 await checkExit(installer.compileRdkit());12})();13async function checkExit(promise) {14 const result = await promise;15 if (result === false) {16 console.error('An error occured');17 process.exit(1);18 }...
topics.js
Source:topics.js
1const Router = require('koa-router')2const jwt = require('koa-jwt')3const router = new Router({ prefix: '/topics' })4const { secret } = require('../config')5const {6 find, findById, create, update, checkExit, listQuestions, checkTopicExit7} = require('../controllers/topics')8const auth = jwt({ secret })9router.get('/', find)10router.get('/:id', checkExit, findById)11router.post('/', auth, create)12router.patch('/:id', auth, checkExit, update)13router.get('/:id/questions', checkTopicExit, listQuestions)...
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1Cypress.Commands.add('checkExit', (url) => {2 cy.request({3 }).then((resp) => {4 expect(resp.status).to.eq(301);5 });6});7Cypress.Commands.add('checkExit', (url) => {8 cy.request({9 }).then((resp) => {10 expect(resp.status).to.eq(301);11 });12});13Cypress.Commands.add('checkExit', (url) => {14 cy.request({15 }).then((resp) => {16 expect(resp.status).to.eq(301);17 });18});19Cypress.Commands.add('checkExit', (url) => {20 cy.request({21 }).then((resp) => {22 expect(resp.status).to.eq(301);23 });24});25Cypress.Commands.add('checkExit', (url) => {26 cy.request({27 }).then((resp) => {28 expect(resp.status).to.eq(301);29 });30});31Cypress.Commands.add('checkExit', (url) => {32 cy.request({33 }).then((resp) => {34 expect(resp.status).to.eq(301);35 });36});37Cypress.Commands.add('checkExit', (url) => {38 cy.request({39 }).then((resp) => {40 expect(resp.status).to.eq(301);41 });42});
Using AI Code Generation
1describe('My First Test', () => {2 it('Visits the Kitchen Sink', () => {3 cy.contains('type').click();4 });5});6describe('My First Test', () => {7 it('Visits the Kitchen Sink', () => {8 cy.contains('type').click();9 });10});11describe('My First Test', () => {12 it('Visits the Kitchen Sink', () => {13 cy.contains('type').click();14 });15});16describe('My First Test', () => {17 it('Visits the Kitchen Sink', () => {18 cy.contains('type').click();19 });20});21describe('My First Test', () => {22 it('Visits the Kitchen Sink', () => {23 cy.contains('type').click();24 });25});26describe('My First Test', () => {27 it('Visits the Kitchen Sink', () => {28 cy.contains('type').click();29 });30});
Using AI Code Generation
1describe('Test', () => {2 it('should exit', () => {3 cy.checkExit();4 });5});6MIT © [Rajeshwar Patlolla](
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.checkExit()4 })5})6Cypress.Commands.add('checkExit', () => {7 cy.get('.exit').should('exist')8})
Using AI Code Generation
1describe('Exit', function () {2 it('Exit', function () {3 cy.get('form').should('not.exist')4 })5})6describe('Exit', function () {7 it('Exit', function () {8 cy.get('form').should('not.exist')9 })10})11describe('Exit', function () {12 it('Exit', function () {13 cy.get('form').should('not.exist')14 })15})16describe('Exit', function () {17 it('Exit', function () {18 cy.get('form').should('not.exist')19 })20})21describe('Exit', function () {22 it('Exit', function () {23 cy.get('form').should('not.exist')24 })25})
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!!