Best JavaScript code snippet using appium-xcuitest-driver
studentLedger.js
Source:studentLedger.js
1var express = require('express');2var router = express.Router();3var pool = require('../model/pool')4var apiResponse = require('../response');5var mssql = require('mssql');6var request = require('request');7var fs = require('fs');8/**9 * @Author: vaishnavi10 * @description:Api to retrive student data from MSsql ledger table(Temp Det_ Cust_ Ledg_ Entry)11 * Return:JSON12 * Params:null13 */14router.get('/getLedger', function(req, res, next) {15 fs.readFile('public/date.txt','utf8',function(err, date) {16 if (!date) {17 var query = "SELECT TOP 10 * FROM [Temp Det_ Cust_ Ledg_ Entry] ORDER BY [Posting Date] desc";18 pool.connection2.then(function(recordset) {19 var request_connection = new mssql.Request();20 request_connection.query(query).then(function(postingDate) {21 var lastUpdatedDate = new Date(postingDate[0]["Posting Date"]);22 fs.writeFile('public/date.txt', postingDate[0]["Posting Date"], function(err) {23 if (err) {24 apiResponse.getData(res, 1001, 'Something went wrong(cannot write to file1)', [{}]);25 } else {26 apiResponse.getData(res, 1002, 'Successfully Synced(1st Sync)', [{}]);27 }28 });29 }).catch(function(err) {30 apiResponse.getData(res, 1001, 'Internal Server Error-1', [{}]);31 });32 }).catch(function(err) {33 apiResponse.getData(res, 1001, 'Internal Server Error-1', [{}]);34 });35 } else {36 fs.readFile('public/date.txt','utf8',function(err, date) {37 38 if (err) throw err;39 else {40 var TempfromDate = new Date(date);41 var fromDate = TempfromDate.toISOString();42 var query = "select * from [Temp Det_ Cust_ Ledg_ Entry] where [Posting Date]>'" + fromDate + "'" + "ORDER BY [Posting Date] desc";43 pool.connection2.then(function(recordset) {44 var requestConnection = pool.request;45 requestConnection.query(query).then(function(ledgerRecord) {46 47 48 if (ledgerRecord.length > 0) {49 requestConnection.cancel();50 51 request.post({52 headers: {53 'content-type': 'application/x-www-form-urlencoded'54 },55 url: req.protocol + '://' + "54.169.111.15:3005" + "/student/dumpLedger",56 form: {57 'ledgers': JSON.stringify(ledgerRecord)58 }59 }, function(error, response, body) {60 61 if (error) {62 apiResponse.getData(res, 1001, 'Something went wrong(Cannot connect to API)', [{}]);63 }else if(body==undefined){64 apiResponse.getData(res, 1006, 'Something went wrong(Body not defined)', [{}]);65 } else {66 67 var newBody = JSON.parse(body);68 if (newBody.statusCode == 1006) {69 fs.writeFile('public/date.txt', ledgerRecord[0]['Posting Date'], function(err) {70 if (err) {71 apiResponse.getData(res, 1001, 'Something Went Wrong(Cannot write to file)', [{}]);72 } else {73 apiResponse.getData(res, 1006, 'Successfully Synced', [{74 "affectedRows": newBody.affectedRows }]);75 }76 });77 } else if (newBody.statusCode == 1007) {78 apiResponse.getData(res, 1007, 'Input Date Missing for getLedge API', [{}]);79 } else if (newBody.statusCode == 1001) {80 apiResponse.getData(res, 1001, 'Internal Server Error(MySql database error)', [{}]);81 } else {82 apiResponse.getData(res, 1002, 'Something went wrong(My sql error)', [{}]);83 }84 }85 });86 87 } else {88 requestConnection.cancel();89 apiResponse.getData(res, 1002, 'No New data to sync', [{}]);90 }91 }).catch(function(err) {92 requestConnection.cancel();93 apiResponse.getData(res, 1001, 'Internal Server Error-2', [{}]);94 });95 }).catch(function(err) {96 apiResponse.getData(res, 1001, 'Internal Server Error-2', [{}]);97 });98 }99 });100 }101 }); //check file exists102})...
21.pooling.js
Source:21.pooling.js
...27 pool = new Pool(poolArgs);28 });29 it("14.1 does not allow users to request connections before initializing the pool", async () => {30 await pool31 .requestConnection()32 .should.be.rejectedWith(33 "must initialize the pool before requesting a connection"34 );35 });36 it("14.2 should reject pool creation with missing arguments", () => {37 (() => {38 const wrong = new Pool(badPoolArgs);39 return wrong;40 }).should.throw(41 "cannot find required argument connectionConfig in constructor arguments"42 );43 });44 it("14.3 Pool can open", async () => {45 await pool.init();46 pool.should.be.ok();47 should.equal(48 pool.free_connections.length,49 10,50 "pool should have 10 connections"51 );52 should.equal(pool.state, "running", "pool should be running after init");53 });54 it("14.4 Allows user to request and return connections", async () => {55 let connection = await pool.requestConnection();56 connection.should.be.ok();57 should.equal(58 pool.free_connections.length,59 9,60 "pool should still have the remaining 9 free connections"61 );62 await pool.releaseConnection(connection);63 should.equal(64 pool.free_connections.length,65 10,66 "pool shoul return to 10 free connections once connection is released"67 );68 });69 it("14.5 Allows users to request over soft limit of connections and closes excess connections upon return", async () => {70 connections = [];71 for (let i = 0; i < 11; i++) {72 connections.push(await pool.requestConnection());73 }74 should.equal(75 Object.keys(pool.all_connections).length,76 11,77 "pool should allow user to go up to 11 connections"78 );79 for (let i = 0; i < connections.length; i++) {80 await pool.releaseConnection(connections[i]);81 }82 should.equal(83 pool.free_connections.length,84 10,85 "pool should remain with 10 free connections when none are in use"86 );87 });88 it("14.6 does not drop below soft limit of connections", async () => {89 await pool._closeConnection(pool.free_connections[0]._id);90 should.equal(91 Object.keys(pool.all_connections).length,92 10,93 "pool should maintain an open a connection when closing to below soft limit"94 );95 });96 it("14.7 Does not close a connection in use on age out", async () => {97 let curr = await pool.requestConnection();98 await pool._closeConnection(curr._id);99 should.equal(100 pool.all_connections[curr._id].ageStatus,101 true,102 "connection should age out but not close"103 );104 await pool.releaseConnection(curr);105 });106 it("14.8 Does not allow the pool to exceed the hard limit of connections", async () => {107 connections = [];108 for (let i = 0; i < 12; i++) {109 connections.push(await pool.requestConnection());110 }111 await pool112 .requestConnection()113 .should.be.rejectedWith("connection hard limit reached");114 for (let i = 0; i < connections.length; i++) {115 await pool.releaseConnection(connections[i]);116 }117 });118 it("14.9 rejects connections that do not belong to the pool", async () => {119 await pool120 .releaseConnection(connectionDoesntBelong)121 .should.be.rejectedWith("connection is not from this pool");122 });123 it("14.10 does not allow release of connections that are not in use/have already been released", async () => {124 const connection = await pool.requestConnection();125 await pool.releaseConnection(connection);126 await pool127 .releaseConnection(connection)128 .should.be.rejectedWith(129 "cannot return a connection that has already been returned to the pool"130 );131 });132 it("14.11 Has changed the connection.close method to return the connection to the pool", async () => {133 const connection = await pool.requestConnection();134 should.equal(135 pool.free_connections.length,136 9,137 "pool should have 9 connections"138 );139 await connection.close();140 should.equal(141 pool.free_connections.length,142 10,143 "calling close on the connection should return it to the pool"144 );145 });146 it("14.12 Pool can close", async () => {147 await pool.closePool();...
express-myconnection.js
Source:express-myconnection.js
1var _mysql,2 _dbConfig,3 _connection, // This is used as a singleton in a single connection strategy4 _pool; // Pool singleton5/**6 * Handling connection disconnects, as defined here: https://github.com/felixge/node-mysql7 */8function handleDisconnect() {9 _connection = _mysql.createConnection(_dbConfig);10 _connection.connect(function (err) {11 if (err) {12 console.log('error when connecting to db:', err);13 setTimeout(handleDisconnect, 2000);14 }15 });16 _connection.on('error', function (err) {17 console.log('db error', err);18 if (err.code === 'PROTOCOL_CONNECTION_LOST') {19 handleDisconnect();20 } else {21 throw err;22 }23 });24}25/**26 * Returns middleware that will handle mysql db connections27 *28 * @param {Object} mysql - mysql module29 * @param {Object} dbConfig - object with mysql db options30 * @param {String} or undefined strategy - default is single strategy31 * @return {Function}32 * @api public33 */34module.exports = function (mysql, dbConfig, strategy) {35 if (null == mysql) throw new Error('Missing mysql module param!');36 if (null == dbConfig) throw new Error('Missing dbConfig module param!');37 if (null == strategy) strategy = 'single';38 // Setting _mysql module ref39 _mysql = mysql;40 // Setting _dbConfig ref41 _dbConfig = dbConfig;42 // Configuring strategies43 switch (strategy) {44 case 'single':45 // Creating single connection instance46 _connection = _mysql.createConnection(dbConfig);47 handleDisconnect(dbConfig);48 break;49 case 'pool':50 // Creating pool instance51 _pool = _mysql.createPool(dbConfig);52 break;53 case 'request':54 // Nothing at this point do be done55 break;56 default:57 throw new Error('Not supported connection strategy!');58 }59 return function (req, res, next) {60 var poolConnection,61 requestConnection,62 releaseFlag;63 switch (strategy) {64 case 'single':65 // getConnection will return singleton connection66 req.getConnection = function (callback) {67 callback(null, _connection);68 }69 break;70 case 'pool':71 // getConnection handled by mysql pool72 req.getConnection = function (callback) {73 // Returning cached connection from a pool, caching is on request level74 if (poolConnection) return callback(null, poolConnection);75 // Getting connection from a pool76 _pool.getConnection(function (err, connection) {77 if (err) return callback(err);78 poolConnection = connection;79 releaseFlag = false;80 callback(null, poolConnection);81 });82 };83 req.releaseConnection = function() {84 if (poolConnection) {85 poolConnection.release();86 poolConnection = null;87 releaseFlag = true;88 }89 };90 break;91 case 'request':92 // getConnection creates new connection per request93 req.getConnection = function (callback) {94 // Returning cached connection, caching is on request level95 if (requestConnection) return callback(null, requestConnection);96 // Creating new connection97 var connection = _mysql.createConnection(dbConfig);98 connection.connect(function (err) {99 if (err) return callback(err);100 requestConnection = connection;101 callback(null, requestConnection);102 });103 }104 break;105 }106 res.on('close', function() {107 // Ending request connection if available108 if (requestConnection) requestConnection.end();109 // Releasing pool connection if available110 if (poolConnection && !releaseFlag) poolConnection.release();111 });112 res.on('finish', function() {113 // Ending request connection if available114 if (requestConnection) requestConnection.end();115 // Releasing pool connection if available116 if (poolConnection && !releaseFlag) poolConnection.release();117 });118 next();119 }...
UserInfoCard.js
Source:UserInfoCard.js
1import React, { Component } from 'react'2import axios from 'axios';3import swal from 'sweetalert';4import {connect} from 'react-redux';5class UserInfoCard extends Component {6 constructor(props){7 super(props);8 this.state={9 buttonDisabled:true10 }11 this.RequestConnection=this.RequestConnection.bind(this);12 }13 RequestConnection = (email) => {14 console.log("EMAIL IS",email)15 console.log("current user IS",this.props.currentUser)16 var data={17 from:this.props.currentUser,18 fromDetails:this.props.currentUserDetails,19 to:email,20 }21 axios.post("http://localhost:3001/user/requestconnection",data)22 .then(function (response) {23 console.log("response",response.data.notifData.body)24 // this.setState({25 // buttonDisabled:false26 // })27 swal("Request Sent", "Request Sent", 'success');28 })29 }30 31 render() {32 var button=<input disabled style={{margin: "12% 11% 24%",border: "1px solid #0073b1",color: "#0073b1",width:"50%"}} type="button" name="connect" value="Connect" onClick={()=>this.RequestConnection(this.props.email)}></input>33 if(this.buttonDisabled!=true)34{35 button=<input style={{margin: "12% 11% 24%",border: "1px solid #0073b1",color: "#0073b1", width:"50%"}} type="button" name="connect" value="Connect" onClick={()=>this.RequestConnection(this.props.email)}></input>36}37 38 return (39 //<div>40 <div class="card">41 <img class="rounded-circle center" src={ require('../../images/avatar.png')} alt="Avatar" style={{width:"75%"}}/>42 <div class="container">43<center> 44 <b ><a style={{fontSize: "100%", color:"black"}} href="#" >{this.props.firstname} {this.props.lastname}</a></b> 45 <p style={{margin:"auto"}}>{this.props.headline}</p> 46 </center> 47 </div>48 49 <div>50 <center>51 {button}52 </center>53 </div>54</div>55 //</div>56 57 )58 59 }60}61function mapStateToProps(state) {62 console.log("State",state);63 return {64 currentUser: state.LoginReducer.current_user,65 currentUserDetails: state.LoginReducer.currentUserDetails,66 userProfileDetails: state.LoginReducer.userProfileDetails67 };68 }...
request_notification.js
Source:request_notification.js
1// import ActionCable from 'actioncable'2// import axios from 'axios'3// function RequestConnection(baseUrl, senderId, callback) {4// var ws_url = 'ws://' + baseUrl + '/v1/request_notif';5// this.updateRequestUrl = 'http://' + baseUrl + '/v1/requests/'; // + requestId6// this.senderId = senderId;7// this.callback = callback;8// this.connection = ActionCable.createConsumer(ws_url);9// this.notifChannel = this.createNotifConnection(senderId);10// }11// RequestConnection.prototype.createNotifConnection = function(myId) {12// var scope = this;13// return this.connection.subscriptions.create({channel: 'RequestNotifChannel', sender: myId}, {14// connected: function() {15// console.log('connected to notification channel!');16// },17// disconnected: function() {},18// received: function(data) {19// var theirReceiverId = data.receiver.guid;20// var requestId = data.request.guid;21// scope.updateRequestUrl += requestId;22// // compares their receiver to self guid (sender guid)23// // if they match, it means the message is for this user24// if (theirReceiverId == myId) {25// // sends a read receipt26// scope.sendReadReceipt();27// return scope.callback(data);28// }29// },30// speak: function() {}31// });32// }33// RequestConnection.prototype.sendReadReceipt = function() {34// axios.put(this.updateRequestUrl, {35// read: true,36// // 'access-token': accessToken,37// // client: client38// }).then(res => console.log(res));39// }...
new.js
Source:new.js
1import model from '../model'2import dbConnection from '../../database/helper'3const service = class {4 constructor () {5 this.requestConnection = dbConnection('request', model)6 }7 save(requestData) {8 return new Promise((resolve, reject)=> {9 let requestConnection = this.requestConnection10 11 requestConnection.sync().then( () => {12 requestConnection.create({13 clientName: requestData.clientName,14 clientEmail: requestData.clientEmail,15 clientPhone: requestData.clientPhone,16 completeAddress: requestData.completeAddress,17 addressComplement: requestData.addressComplement,18 totalPurchase: requestData.totalPurchase,19 servicesSum: requestData.servicesSum,20 deliveryTax: requestData.deliveryTax,21 requestOperationTax: requestData.requestOperationTax,22 status: requestData.status,23 addressLat: requestData.addressLat,24 addressLng: requestData.addressLng,25 transactionOperationTax: requestData.transactionOperationTax26 })27 .then((newRequest)=>{28 requestConnection.sequelize.close()29 resolve(newRequest)30 })31 .catch((err)=>{32 requestConnection.sequelize.close()33 reject({34 message: 'Erro ao criar novo pedido no banco de dados',35 data: err36 })37 })38 })39 })40 41 }42}...
network.js
Source:network.js
1let requestConnection = document.querySelectorAll('.btn-sm')2console.log(requestConnection)3Array.from(requestConnection).forEach(function(element) {4 element.addEventListener('click', function(e){5 console.log(e.target.dataset.name)6 console.log(e.target.dataset.img)7 let id = e.target.dataset.id8 let user = e.target.dataset.name9 let mentorName = e.target.dataset.mentor10 let menteePic = e.target.dataset.img11 let goals = e.target.dataset.goals12 let stack= e.target.dataset.stack13 14 fetch('requestConnection', {15 method: 'put',16 headers: {'Content-Type': 'application/json'},17 body: JSON.stringify({18 'id' : id,19 'user': user,20 'mentorName': mentorName,21 "menteePic": menteePic,22 'goals': goals,23 'stack': stack24 })25 })26 .then(response => {27 if (response.ok) return response.json()28 })29 .then(data => {30 console.log(data)31 window.location.reload(true)32 })33 });...
requestConnection.test.js
Source:requestConnection.test.js
1import test from 'tape';2import requestConnection from './requestConnection';3import { actionTypes } from '../constants';4test('requestConnection tests', (t) => {5 const actual = requestConnection();6 const expected = { type: actionTypes.CONNECTION_REQUESTED };7 t.same(actual, expected, 'it should create a CONNECTION_REQUESTED action.');8 t.end();...
Using AI Code Generation
1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const expect = chai.expect;6const PORT = 4723;7const HOST = 'localhost';8const config = {9};10const driver = wd.promiseChainRemote(URL);11describe('test', () => {12 before(async () => {13 await driver.init(config);14 });15 it('should be able to request connection', async () => {16 await driver.requestConnection();17 });18});19const commands = {};20commands.requestConnection = async function () {21 const {webSocketDebuggerUrl} = await this.startWebDriverAgentSession();22 if (!webSocketDebuggerUrl) {23 log.errorAndThrow(`Cannot connect to the remote debugger. Original error: ${err}`);24 }25 log.info(`Debugger web socket url: ${webSocketDebuggerUrl}`);26 this.remote = new RemoteDebugger({27 isRealDevice: this.isRealDevice(),
Using AI Code Generation
1var wd = require('wd');2driver.init({3}).then(function() {4 return driver.setImplicitWaitTimeout(5000);5}).then(function() {6 return driver.requestConnection('com.apple.Preferences');7}).then(function() {8 return driver.quit();9}).done();10var wd = require('wd');11driver.init({12}).then(function() {13 return driver.setImplicitWaitTimeout(5000);14}).then(function() {15 return driver.requestConnection('com.apple.Preferences');16}).then(function() {17 return driver.quit();18}).done();
Using AI Code Generation
1const wd = require('webdriverio');2const opts = {3 capabilities: {4 }5};6async function main () {7 let client = await wd.remote(opts);8 let sessionId = client.requestHandler.sessionID;9 let udid = client.requestHandler.sessionID;10 console.log(sessionId);11 console.log(udid);12 await client.deleteSession();13}14main();15const wd = require('webdriverio');16const opts = {17 capabilities: {18 }19};20async function main () {21 let client = await wd.remote(opts);22 let sessionId = client.requestHandler.sessionID;23 let udid = client.requestHandler.sessionID;24 console.log(sessionId);25 console.log(udid);26 await client.deleteSession();27}28main();
Using AI Code Generation
1driver.init({2}).then(function () {3 return driver.requestConnection();4});5driver.init({6}).then(function () {7 return driver.requestConnection();8});9driver.init({10}).then(function () {11 return driver.requestConnection();12});13driver.init({14}).then(function () {15 return driver.requestConnection();16});
Using AI Code Generation
1driver.init({2}).then(function () {3 return driver.requestConnection();4}).then(function () {5 return driver.setImplicitWaitTimeout(10000);6}).then(function () {7 return driver.waitForElementByAccessibilityId("test", 10000);8}).then(function (el) {9 return el.click();10}).fin(function () {11 return driver.quit();12}).done();13driver.init({14}).then(function () {15 return driver.requestConnection();16}).then(function () {17 return driver.setImplicitWaitTimeout(10000);18}).then(function () {19 return driver.waitForElementByAccessibilityId("test", 10000);20}).then(function (el
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5 .init(desired)6 .then(function() {7 return driver.requestConnection();8 })9 .then(function() {10 })11 .fin(function() { return driver.quit(); })12 .done();13var wd = require('wd');14var assert = require('assert');15var desired = {16};17 .init(desired)18 .then(function() {19 return driver.requestConnection();20 })21 .then(function() {22 })23 .fin(function() { return driver.quit(); })24 .done();25var wd = require('wd');26var assert = require('assert');27var desired = {28};29 .init(desired)30 .then(function() {31 return driver.requestConnection();32 })
Using AI Code Generation
1const wd = require('wd');2const { exec } = require('child_process');3const { getPort } = require('portfinder');4const { appium } = require('appium-xcuitest-driver');5const { appiumServer } = require('appium');6const { iosSimulator } = require('appium-ios-simulator');7const { XCUITestDriver } = require('appium-xcuitest-driver');8const { XCUITestSimulatorDriver } = require('appium-xcuitest-driver');9const { XCUITestSimulatorUICatalogApp } = require('appium-xcuitest-driver');10const { XCUITestSimulatorSystemLogger } = require('appium-xcuitest-driver');11const { XCUITestSimulatorDriverConfig } = require('appium-xcuitest-driver');12const { XCUITestCapabilities } = require('appium-xcuitest-driver');13const { XCUITestSimulator, XCUITestSimulatorDevice } = require('appium-ios-simulator');14const { XCUITestSimulatorLog } = require('appium-ios-simulator');15const { XCUITestSimulatorLogCapture } = require('appium-ios-simulator');16const { XCUITestSimulatorLogPlugin } = require('appium-ios-simulator');17const { XCUITestSimulatorLogPluginManager } = require('appium-ios-simulator');18const { XCUITestSimulatorLogPluginSimctl } = require('appium-ios-simulator');19const { XCUITestSimulatorLogPluginSyslog } = require('appium-ios-simulator');20const { XCUITestSimulatorLogPluginXcode } = require('appium-ios-simulator');21const { XCUITestSimulatorLogPluginXcode6 } = require('appium-ios-simulator');22const { XCUITestSimulatorLogPluginXcode7 } = require('appium-ios-simulator');23const { XCUITestSimulatorLogPluginXcode8 } = require('appium-ios-simulator');24const { XCUITestSimulatorLogPluginXcode9 } = require('appium-ios-simulator');25const { XCUITestSimulatorLogPluginXcode10 } = require('appium-ios-simulator');26const { XCUITestSimulatorLogPluginXcode11
Using AI Code Generation
1const request = require('request');2const requestConnection = require('./lib/requestConnection');3const json = {desiredCapabilities: {app: 'com.example.apple-samplecode.UICatalog'}};4const requestConnectionJson = {udid: 'auto'};5request.post({url: url, json: json}, (err, res, body) => {6 if (err) {7 console.log(err);8 } else {9 const sessionId = body.sessionId;10 requestConnection.requestConnection(url, sessionId, requestConnectionJson, (err, res, body) => {11 if (err) {12 console.log(err);13 } else {14 console.log(body);15 }16 });17 }18});19const request = require('request');20const requestConnection = (url, sessionId, json, cb) => {21 request.post({url: `${url}/session/${sessionId}/wda/requestConnection`, json: json}, cb);22};23module.exports.requestConnection = requestConnection;24{25 {26 "availability": "(available)",27 "os": {28 }29 },30 {31 "availability": "(available)",32 "os": {33 }
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!