Best JavaScript code snippet using webdriverio-monorepo
offline.functional.tests.js
Source:offline.functional.tests.js
...66 $assert.fail('should have failed to lookup deleted server record');67 },68 fail: function(error) {}69 }];70 return performActions(actions);71}), $test('vanilla pull - insert / update / delete').description('performs insert, update and delete on the server and pulls each of them individually').checkAsync(function() {72 var actions = ['serverinsert', 'vanillapull', 'clientlookup', function(result) {73 $assert.areEqual(result.id, serverValue.id);74 $assert.areEqual(result.text, serverValue.text);75 }, 'serverupdate', 'vanillapull', 'clientlookup', function(result) {76 $assert.areEqual(result.id, serverValue.id);77 $assert.areEqual(result.text, serverValue.text);78 }, 'serverdelete', 'vanillapull', 'clientlookup', {79 success: function(result) {80 $assert.fail('client lookup should have failed');81 },82 fail: function(error) {}83 }];84 return performActions(actions);85}), $test('Vanilla pull - default page size').checkAsync(function() {86 return performPull(60, 'vanillapull');87}), $test('Vanilla pull - tiny page size').checkAsync(function() {88 pullPageSize = 1;89 return performPull(5, 'vanillapull');90}), $test('Vanilla pull - zero records').checkAsync(function() {91 pullPageSize = 4;92 return performPull(0, 'vanillapull');93}), $test('Vanilla pull - single page').checkAsync(function() {94 pullPageSize = 4;95 return performPull(2, 'vanillapull');96}), $test('Vanilla pull - record count exactly matches page size').checkAsync(function() {97 pullPageSize = 4;98 return performPull(4, 'vanillapull');99}), $test('Vanilla pull - multiple pages').checkAsync(function() {100 pullPageSize = 2;101 return performPull(4, 'vanillapull');102}), $test('Incremental pull - default page size').checkAsync(function() {103 return performPull(60, 'incrementalpull');104}), $test('Incremental pull - tiny page size').checkAsync(function() {105 pullPageSize = 1;106 return performPull(5, 'incrementalpull');107}), $test('Incremental pull - zero records').checkAsync(function() {108 return performPull(0, 'incrementalpull');109}), $test('Incremental pull - single page').checkAsync(function() {110 pullPageSize = 4;111 return performPull(2, 'incrementalpull');112}), $test('Incremental pull - record count exactly matches page size').checkAsync(function() {113 pullPageSize = 4;114 return performPull(4, 'incrementalpull');115}), $test('Incremental pull - multiple pages').checkAsync(function() {116 pullPageSize = 2;117 return performPull(4, 'incrementalpull');118}), $test('Push with response 409 - conflict not handled').description('verifies that push behaves as expected if error is 409 and conflict is not handled').checkAsync(function() {119 var actions = ['serverinsert', 'clientinsert', 'push', function(conflicts) {120 $assert.areEqual(conflicts.length, 1);121 $assert.areEqual(conflicts[0].getError().request.status, 409);122 }];123 return performActions(actions);124}), $test('Push with response 409 - conflict handled').description('verifies that push behaves as expected if error is 409 and conflict is handled').checkAsync(function() {125 syncContext.pushHandler = {};126 syncContext.pushHandler.onConflict = function(pushError) {127 $assert.areEqual(pushError.getError().request.status, 409);128 return pushError.changeAction('update');129 };130 var actions = ['serverinsert', 'clientinsert', 'push', function(conflicts) {131 $assert.areEqual(conflicts.length, 0);132 }, 'serverlookup', function(result) {133 $assert.areEqual(result.id, clientValue.id);134 $assert.areEqual(result.text, clientValue.text);135 }];136 return performActions(actions);137}), $test('Push with response 412 - conflict not handled').description('verifies that push behaves as expected if error is 412 and conflict is not handled').checkAsync(function() {138 var actions = ['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'push', function(conflicts) {139 $assert.areEqual(conflicts.length, 1);140 $assert.areEqual(conflicts[0].getError().request.status, 412);141 }];142 return performActions(actions);143}), $test('Push with response 412 - conflict handled').description('verifies that push behaves as expected if error is 412 and conflict is handled').checkAsync(function() {144 syncContext.pushHandler = {};145 syncContext.pushHandler.onConflict = function(pushError) {146 $assert.areEqual(pushError.getError().request.status, 412);147 var newValue = pushError.getClientRecord();148 newValue.version = pushError.getServerRecord().version;149 return pushError.update(newValue);150 };151 var actions = ['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'push', function(conflicts) {152 $assert.areEqual(conflicts.length, 0);153 }, 'serverlookup', function(result) {154 $assert.areEqual(result.id, clientValue.id);155 $assert.areEqual(result.text, clientValue.text);156 }];157 return performActions(actions);158}), $test('Push - connection error unhandled').checkAsync(function() {159 filter = function(req, next, callback) {160 callback(null, {161 status: 400,162 responseText: '{"error":"some error"}'163 });164 };165 var actions = ['clientinsert', 'push', {166 success: function(conflicts) {167 $assert.fail('should have failed');168 },169 fail: function(error) {170 $assert.isNotNull(error);171 }172 }];173 return performActions(actions);174}), $test('Push - connection error handled').checkAsync(function() {175 var fail = true;176 filter = function(req, next, callback) {177 if (fail) {178 callback(null, {179 status: 400,180 responseText: '{"error":"some error"}'181 });182 } else {183 next(req, callback);184 }185 };186 syncContext.pushHandler = {onError: function(pushError) {187 fail = false;188 pushError.isHandled = true;189 }};190 var actions = ['clientinsert', 'push', 'serverlookup', function(serverValue) {191 $assert.isNotNull(serverValue);192 $assert.areEqual(serverValue.text, clientValue.text);193 }];194 return performActions(actions);195}), $test('Pull - pending changes on client').description('Verifies that pull leaves records that are edited on the client untouched').checkAsync(function() {196 var actions = ['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'vanillapull', 'clientlookup', function(result) {197 $assert.areNotEqual(result.text, serverValue.text);198 }];199 return performActions(actions);200}), $test('pushError.update() test').description('Verifies correctness of error handling function pushError.update()').checkAsync(function() {201 syncContext.pushHandler = {};202 syncContext.pushHandler.onConflict = function(pushError) {203 $assert.areEqual(pushError.getError().request.status, 412);204 var newValue = pushError.getClientRecord();205 newValue.version = pushError.getServerRecord().version;206 return pushError.update(newValue);207 };208 var actions = ['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'push', function(conflicts) {209 $assert.areEqual(conflicts.length, 0);210 }, 'serverlookup', function(result) {211 $assert.areEqual(result.id, clientValue.id);212 $assert.areEqual(result.text, clientValue.text);213 }];214 return performActions(actions);215}), $test('pushError.cancelAndUpdate() test').description('Verifies correctness of error handling function pushError.cancelAndUpdate()').checkAsync(function() {216 syncContext.pushHandler = {};217 syncContext.pushHandler.onConflict = function(pushError) {218 $assert.areEqual(pushError.getError().request.status, 412);219 var newValue = pushError.getClientRecord();220 newValue.version = pushError.getServerRecord().version;221 return pushError.cancelAndUpdate(newValue).then(function() {222 syncContext.pushHandler = undefined;223 });224 };225 var actions = ['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'push', function(conflicts) {226 $assert.areEqual(conflicts.length, 0);227 }, 'clientlookup', function(result) {228 $assert.areNotEqual(result.version, clientValue.version);229 }, 'serverlookup', function(result) {230 $assert.areEqual(result.id, serverValue.id);231 $assert.areEqual(result.text, serverValue.text);232 $assert.isNotNull(result.text);233 }, 'push', function(conflicts) {234 $assert.areEqual(conflicts.length, 0);235 }, 'serverlookup', function(result) {236 $assert.areEqual(result.id, serverValue.id);237 $assert.areEqual(result.text, serverValue.text);238 $assert.isNotNull(result.text);239 }];240 return performActions(actions);241}), $test('pushError.cancelAndDiscard() test').description('Verifies correctness of error handling function pushError.cancelAndDiscard()').checkAsync(function() {242 syncContext.pushHandler = {};243 syncContext.pushHandler.onConflict = function(pushError) {244 $assert.areEqual(pushError.getError().request.status, 412);245 var newValue = pushError.getClientRecord();246 newValue.version = pushError.getServerRecord().version;247 return pushError.cancelAndDiscard(newValue).then(function() {248 syncContext.pushHandler = undefined;249 });250 };251 var actions = ['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'push', function(conflicts) {252 $assert.areEqual(conflicts.length, 0);253 }, 'clientlookup', {254 success: function(result) {255 $assert.fail('client lookup should have failed');256 },257 fail: function(error) {}258 }, 'serverlookup', function(result) {259 $assert.areEqual(result.id, serverValue.id);260 $assert.areEqual(result.text, serverValue.text);261 $assert.isNotNull(result.text);262 }, 'push', function(conflicts) {263 $assert.areEqual(conflicts.length, 0);264 }, 'serverlookup', function(result) {265 $assert.areEqual(result.id, serverValue.id);266 $assert.areEqual(result.text, serverValue.text);267 $assert.isNotNull(result.text);268 }];269 return performActions(actions);270}), $test('Multiple records pushed, one conflict - conflict handled').description('Verifies that a conflict, if handled, does not prevent other records from being pushed').checkAsync(function() {271 syncContext.pushHandler = {};272 syncContext.pushHandler.onConflict = function(pushError) {273 $assert.areEqual(pushError.getError().request.status, 412);274 var newValue = pushError.getClientRecord();275 newValue.version = pushError.getServerRecord().version;276 return pushError.update(newValue);277 };278 var serverId1,279 serverId2,280 serverId3,281 clientValue1,282 clientValue2,283 clientValue3;284 var actions = ['serverinsert', 'vanillapull', 'clientupdate', function() {285 serverId1 = serverValue.id;286 clientValue1 = clientValue;287 currentId = generateGuid();288 }, 'serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', function() {289 serverId2 = serverValue.id;290 clientValue2 = clientValue;291 currentId = generateGuid();292 }, 'serverinsert', 'vanillapull', 'clientupdate', function() {293 serverId3 = serverValue.id;294 clientValue3 = clientValue;295 currentId = generateGuid();296 }, 'push', function() {297 currentId = serverId1;298 }, 'serverlookup', function(result) {299 $assert.isNotNull(result);300 $assert.isNotNull(result.text);301 $assert.areEqual(result.text, clientValue1.text);302 }, function() {303 currentId = serverId2;304 }, 'serverlookup', function(result) {305 $assert.isNotNull(result);306 $assert.isNotNull(result.text);307 $assert.areEqual(result.text, clientValue2.text);308 }, function() {309 currentId = serverId3;310 }, 'serverlookup', function(result) {311 $assert.isNotNull(result);312 $assert.isNotNull(result.text);313 $assert.areEqual(result.text, clientValue3.text);314 }];315 return performActions(actions);316}), $test('Multiple records pushed, one conflict - conflict not handled').description('Verifies that a conflict, if unhandled, does not prevent other records from being pushed').checkAsync(function() {317 var serverId1,318 serverId2,319 serverId3,320 clientValue1,321 clientValue2,322 clientValue3;323 var actions = ['serverinsert', 'vanillapull', 'clientupdate', function() {324 serverId1 = serverValue.id;325 clientValue1 = clientValue;326 currentId = generateGuid();327 }, 'serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', function() {328 serverId2 = serverValue.id;329 clientValue2 = clientValue;330 currentId = generateGuid();331 }, 'serverinsert', 'vanillapull', 'clientupdate', function() {332 serverId3 = serverValue.id;333 clientValue3 = clientValue;334 currentId = generateGuid();335 }, 'push', function(conflicts) {336 $assert.areEqual(conflicts.length, 1);337 }, function() {338 currentId = serverId1;339 }, 'serverlookup', function(result) {340 $assert.isNotNull(result);341 $assert.isNotNull(result.text);342 $assert.areEqual(result.text, clientValue1.text);343 }, function() {344 currentId = serverId2;345 }, 'serverlookup', function(result) {346 $assert.isNotNull(result);347 $assert.isNotNull(result.text);348 $assert.areNotEqual(result.text, clientValue2.text);349 }, function() {350 currentId = serverId3;351 }, 'serverlookup', function(result) {352 $assert.isNotNull(result);353 $assert.isNotNull(result.text);354 $assert.areEqual(result.text, clientValue3.text);355 }];356 return performActions(actions);357}), $test('Push - A handled conflict should be considered handled if isHandled is set to false').checkAsync(function() {358 syncContext.pushHandler = {};359 syncContext.pushHandler.onConflict = function(pushError) {360 $assert.areEqual(pushError.getError().request.status, 412);361 var newValue = pushError.getClientRecord();362 newValue.version = pushError.getServerRecord().version;363 return pushError.cancelAndDiscard(newValue).then(function() {364 pushError.isHandled = false;365 });366 };367 var actions = ['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'push', function(conflicts) {368 $assert.areEqual(conflicts.length, 1);369 }, 'clientlookup', {370 success: function(result) {371 $assert.fail('client lookup should have failed');372 },373 fail: function(error) {}374 }, 'serverlookup', function(result) {375 $assert.areEqual(result.id, serverValue.id);376 $assert.areEqual(result.text, serverValue.text);377 $assert.isNotNull(result.text);378 }];379 return performActions(actions);380}), $test('Push - A handled conflict should be considered unhandled if onConflict fails').checkAsync(function() {381 syncContext.pushHandler = {};382 syncContext.pushHandler.onConflict = function(pushError) {383 $assert.areEqual(pushError.getError().request.status, 412);384 var newValue = pushError.getClientRecord();385 newValue.version = pushError.getServerRecord().version;386 return pushError.cancelAndDiscard(newValue).then(function() {387 throw 'some error';388 });389 };390 var actions = ['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'push', function(conflicts) {391 $assert.areEqual(conflicts.length, 1);392 }, 'clientlookup', {393 success: function(result) {394 $assert.fail('client lookup should have failed');395 },396 fail: function(error) {}397 }, 'serverlookup', function(result) {398 $assert.areEqual(result.id, serverValue.id);399 $assert.areEqual(result.text, serverValue.text);400 $assert.isNotNull(result.text);401 }];402 return performActions(actions);403}), $test('Conflict detection - insert').checkAsync(function() {404 return verifyConflict(['serverinsert', 'clientinsert', 'push'], 409);405}), $test('Conflict detection - update').checkAsync(function() {406 return verifyConflict(['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'push'], 412);407}), $test('Conflict detection - delete').checkAsync(function() {408 return verifyConflict(['serverinsert', 'vanillapull', 'serverupdate', 'clientupdate', 'clientdelete', 'push'], 412);409}));410function verifyConflict(actions, expectedResponseCode) {411 syncContext.pushHandler = {};412 syncContext.pushHandler.onConflict = function(serverRecord, clientRecord, pushError) {413 $assert.areEqual(pushError.getError().request.status, expectedResponseCode);414 };415 actions.push(function(conflicts) {416 $assert.areEqual(conflicts.length, 1);417 });418 return performActions(actions);419}420function performActions(actions) {421 currentId = generateGuid();422 var chain = Platform.async(function(callback) {423 callback();424 })();425 for (var i in actions) {426 chain = performAction(chain, actions[i]);427 }428 return chain;429}430function performAction(chain, action) {431 var record;432 return chain.then(function(result) {433 if (action && action.success) {434 return action.success(result);435 }436 if (_.isFunction(action)) {437 return action(result);438 }439 switch (action) {440 case 'clientinsert':441 record = generateRecord('client-insert');442 return syncContext.insert(testTableName, record).then(function(result) {443 clientValue = result;444 return result;445 });446 case 'clientupdate':447 record = generateRecord('client-update');448 return syncContext.update(testTableName, record).then(function(result) {449 clientValue = result;450 return result;451 });452 case 'clientdelete':453 record = generateRecord();454 return syncContext.del(testTableName, record).then(function(result) {455 clientValue = undefined;456 return result;457 });458 case 'clientlookup':459 return syncContext.lookup(testTableName, currentId);460 case 'clientread':461 return syncContext.read(new Query(testTableName));462 case 'serverinsert':463 record = generateRecord('server-insert');464 return table.insert(record).then(function(result) {465 serverValue = result;466 return result;467 });468 case 'serverupdate':469 record = generateRecord('server-update');470 return table.update(record).then(function(result) {471 serverValue = result;472 return result;473 });474 case 'serverdelete':475 record = generateRecord();476 return table.del(record).then(function(result) {477 serverValue = undefined;478 return result;479 });480 case 'serverlookup':481 return table.lookup(currentId);482 case 'serverread':483 return table.read(query);484 case 'push':485 return syncContext.push();486 case 'vanillapull':487 return syncContext.pull(query, null, {pageSize: pullPageSize});488 case 'incrementalpull':489 return syncContext.pull(query, 'queryId', {pageSize: pullPageSize});490 default:491 throw new Error('Unsupported action : ' + action);492 }493 }, function(error) {494 if (action && action.fail) {495 return action.fail(error);496 } else {497 $assert.fail('Unexpected failure while running action : ' + action);498 $assert.fail(error);499 throw error;500 }501 });502}503function performPull(recordCount, pullType) {504 var numServerRequests = 0;505 var actions = [function() {506 return populateServerTable(textPrefix, recordCount);507 }, pullType, 'clientread', function(result) {508 $assert.areEqual(result.length, recordCount);509 }];510 return performActions(actions);511}512function populateServerTable(textPrefix, count) {513 var numInsertedRecords = 0;514 var chain = Platform.async(function(callback) {515 callback();516 })();517 for (var i = 0; i < count; i++) {518 chain = insertRecord(chain, {519 id: generateGuid(),520 text: generateText(textPrefix),521 complete: false522 });523 }524 return chain;...
pebble-js-app.js
Source:pebble-js-app.js
...61 case 0: console.log("MENU0.0: Turn on AC");62 if(vehicleID === null)63 doLogin(['getVehicles',{name:"Enable A/C",cmd:"auto_conditioning_start",method:'POST'}]);64 else65 performActions([{name:"Enable A/C",cmd:"auto_conditioning_start",method:'POST'}]);66 break;67 case 1:68 console.log("MENU0.1: Climate stats");69 if(vehicleID === null)70 doLogin(['getVehicles','getClimateState']);71 else72 getClimateState([]);73 break;74 case 10:75 console.log("MENU1.0: Start charge");76 performActions([77 {name:"Open charge door",cmd:"charge_port_door_open",method:'POST'},78 {name:"Start charge",cmd:"charge_start",method:'POST'}]79 );80 break;81 case 11:82 console.log("MENU1.1: Get range");83 performActions(['getChargedState']);84 break;85 case 12:86 console.log("MENU1.2: Stop charge");87 performActions([{name:"Stop charging",cmd:"charge_stop",method:'POST'}]);88 break;89 case 20:90 console.log("MENU2.0: Lock doors");91 performActions([{name:"Lock doors",cmd:"door_lock",method:'POST'}]);92 break;93 case 21:94 console.log("MENU2.1: Honk");95 performActions([{name:"Honk horn",cmd:"honk_horn",method:'POST'}]);96 break;97 case 22:98 console.log("MENU2.2: Flash lights");99 performActions([{name:"Flash lights",cmd:"flash_lights",method:'POST'}]);100 break;101 case 23:102 console.log("MENU2.3: Reconnect vid="+ vehicleID);103 Pebble.showSimpleNotificationOnPebble("Reconnect", "I will attempt to reconnect to the API, find your car and get info about it.");104 performActions(['resetdata','doLogin','getVehicles','getChargedState','disablePassiveRequests']);105 break;106 case 24:107 console.log("MENU2.4: Get Vehicle info vid="+ vehicleID);108 performActions([{name:'Get vehicle info',cmd:'vehicle_state',method:'GET'}]);109 break;110 case 25:111 console.log("MENU2.5: Turn off A/C vid="+ vehicleID);112 performActions([{name:'Turn off A/C',cmd:'auto_conditioning_stop',method:'POST'}]);113 break;114 case 26:115 console.log("MENU2.6: About");116 Pebble.showSimpleNotificationOnPebble("About Tesla FTW!", "By Erik de Bruijn.\nTesla is a brand owned by Tesla Motors. This application is not affiliated or endorsed by Tesla Motors.\n\nDedicated to Elon Musk who is a big inspiration to me and whom I hope to meet one day.\n\nEnjoy, Erik");117 break;118 case 99:119 console.log("99: App loaded");120 performActions(['resetdata']);121 break;122 default:123 console.log("menu option undef.");124 break;125 }126 }127}128function performActions(actions) {129 console.log("performActions("+actions+")");130 var action = actions.shift();131 console.log("performActions: next up is "+action+"\n");132 if(vehicleID === null) {133 if(action != 'getVehicles')134 actions.unshift('getVehicles');135 if(action != 'doLogin')136 actions.unshift('doLogin');137 }138 switch(action) {139 case 'getVehicles': getVehicles(actions); break;140 case 'getChargedState': getChargedState(actions); break;141 case 'getClimateState': getClimateState(actions); break;142 case 'disablePassiveRequests': passiveRequest = false; break;143 case 'enablePassiveRequests': passiveRequest = true; break;144 case 'resetdata':145 console.log("Resetting vars...");146 passiveRequest = true;147 chargeData = null;148 climateData = null;149 vehicleID = null;150 localStorage.removeItem('vehicleID');151 retries = 3;152 // performActions(actions);153 break;154 }155 if(typeof action == 'object' && action.cmd) {156 performCommand(action,actions);157 }158 if(--retries > 0 && (vehicleID === null)) {159 console.log("Calling performActions() from performActions() itself (retries = "+retries+").");160 return performActions(actions);161 }162}163// IO calls to API uses code from: https://github.com/hjespers/teslams164function doLogin(actions) {165 // if(access_token)166 // return performActions(actions); // perform remaining actions167 //FIXME: get access_token168 console.log("doLogin(): Attempting to receive a token");169 var data = new FormData();170 data.append('grant_type','password');171 data.append('client_id',TESLA_CLIENT_ID);172 data.append('client_secret',TESLA_CLIENT_SECRET);173 data.append('email', settingStore.username.trim());174 data.append('password', settingStore.password.trim());175 var req = new XMLHttpRequest();176 req.TimeOut = 2000;177 req.open('POST', portal+'/oauth/token',true);178 req.onreadystatechange = function(e) {179 if (req.readyState == 4) {180 console.log("doLogin() response (http: "+req.status+"): " + this.responseText);181 if(req.status == 200) {182 try { data = JSON.parse(this.responseText); } catch(err) { return cb(new Error('login failed')); }183 if (typeof data != "object") return cb(new Error('expecting a JSON object from Tesla Motors cloud service'));184 console.log(data);185 access_token = data.access_token;186 current_unixtime = Math.floor(Date.now() / 1000);187 localStorage.setItem('access_token_expires_at',data.expires_in + current_unixtime);188 localStorage.setItem('access_token',data.access_token);189 console.log('access_token ' + access_token);190 Pebble.sendAppMessage({"99":"Success!!"});191 performActions(actions); // perform remaining actions192 } else {193 console.log("Failed. "+ req.status.toString()+ " "+e.error+" " +req.error+ "response Text"+req.responseText);194 Pebble.showSimpleNotificationOnPebble("Connection problem", "Could not verify username and password at "+ portal + '/login. Invalid HTTPS response.');195 }196 }197 };198 req.onload = function(e) {199 if (req.readyState == 4) {200 console.log("Response (status: "+req.status+"): " + this.responseText);201 if(req.status == 200) {202 Pebble.sendAppMessage({"99":"Success!!"});203 performActions(actions); // perform remaining actions204 } else {205 console.log("Failed. "+ req.status.toString()+ " "+e.error+" " +req.error);206 Pebble.sendAppMessage({"99":"Login failed!"});207 Pebble.showSimpleNotificationOnPebble("Login failure", "There was a login error (username="+settingStore.username+"): "+ req.status.toString()+ " "+e.error);208 }209 }210 };211 req.send(data);212}213// IO calls to API uses code from: https://github.com/hjespers/teslams214function getVehicles(actions) {215 console.log("getVehicles(): Attempting to receive an array (!) of vehicles :)");216 var req = new XMLHttpRequest();217 req.open('GET', portal +'/api/1/vehicles', true);218 req.setRequestHeader('Authorization','Bearer '+access_token);219 req.onload = function(e) {220 if (req.readyState == 4) {221 console.log("Response (status: "+req.status+"): " + this.responseText);222 if(req.status == 200) {223 console.log("HTTP GET success.\n");224 try { data = JSON.parse(this.responseText); } catch(err) { return cb(new Error('login failed')); }225 if (typeof data != "object") return cb(new Error('expecting a JSON object from Tesla Motors cloud service'));226 console.log("Vehicles (num="+ data.response.length+ "): ");227 if(data.response.length !== 0) {228 vehicleData = data.response[0];229 if(data.response.length > 1)230 Pebble.showSimpleNotificationOnPebble("Vehicle list", "Multiple vehicles were listed ("+data.length+"). Using the first one: "+vehicleData.id_s);231 if(data.response.length == 1)232 Pebble.showSimpleNotificationOnPebble("Vehicle list", "1 vehicle found: "+vehicleData.id_s+": "+JSON.stringify(vehicleData));233 localStorage.setItem('vehicleData', vehicleData);234 localStorage.setItem('vehicleID', vehicleData.id_s);235 vehicleID = vehicleData.id_s;236 console.log("Using vehicle ID "+vehicleID);237 performActions(actions); // perform remaining actions238 } else239 Pebble.showSimpleNotificationOnPebble("Vehicle list", "No vehicles were listed.");240 } else {241 console.log("Failed.\n");242 Pebble.sendAppMessage({"99":"Failed retrieval!"});243 }244 }245 };246 req.send(null);247}248function getChargedState(actions) {249 console.log("getChargedState(vid="+vehicleID+",nextActions="+actions+")");250 if(chargeData) {251 showChargedState(chargeData);252 return;253 }254 var req = new XMLHttpRequest();255 var url = portal +'/api/1/vehicles/'+vehicleID+'/data_request/charge_state';256 console.log("GET "+url);257 req.open('GET', url, true);258 req.setRequestHeader('Authorization','Bearer '+access_token);259 req.setRequestHeader('User-Agent', 'Model S 2.1.79 (Nexus 5; Android REL 4.4.4; en_US)');260 req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');261 req.setRequestHeader('Accept-Encoding', 'gzip,deflate');262 req.onload = function(e) {263 if (req.readyState == 4) {264 console.log("Response (status: "+req.status+"): " + this.responseText);265 if(req.status == 200) {266 console.log("HTTP GET success.\n");267 try { data = JSON.parse(this.responseText); } catch(err) { return cb(new Error('Data couldnt be parsed. Is it JSON? '+this.responseText)); }268 if (typeof data != "object") return cb(new Error('expecting a JSON object from Tesla Motors cloud service'));269 console.log("Results (num="+ data.length+ "): ");270 console.log(data);271 chargeData = data.response;272 console.log("chargeData: "+chargeData);273 if(data.length !== 0) {274 theData = data[0];275 if(!passiveRequest) // Don't show popup if its not a GUI initiated request.276 showChargedState(data);277 if(typeof chargeData == "object")278 Pebble.sendAppMessage({ "batteryPerc": makeChargeTxtMini(chargeData) + "" },connectOkHandler,connectFailHandler);279 performActions(actions); // perform remaining actions280 }281 } else {282 console.log("Failed.\n"+this.getAllResponseHeaders());283 Pebble.sendAppMessage({"99":"Failed!!"});284 }285 }286 };287 req.send(null);288}289function showChargedState(data) {290 var chargeTxt = makeChargeTxt(data);291 Pebble.showSimpleNotificationOnPebble("Battery " + data.battery_level + "%", chargeTxt);292}293function makeChargeTxt(data) {294 var chargeTxt = data.charging_state+" ";295 if(data.charging_state == 'Charging')296 chargeTxt = data.charging_state + " " + (parseInt(data.charge_rate*settings.distance_factor,10)) + " " + settings.distance_unit + "/h\n";297 chargeTxt = chargeTxt + "Ideal range "+parseInt(data.ideal_battery_range*settings.distance_factor,10)+" " + settings.distance_unit + " ";298 var chargePhasesStr = (data.charger_phases >= 2 ? (data.charger_phases+"x") : "");299 var chargePowerStr = "";300 if(data.charger_voltage > 0)301 chargePowerStr = chargePhasesStr + data.charger_voltage + "V " + data.charger_actual_current + "A " +302 parseInt(data.charger_voltage * data.charger_actual_current/100,10)/10 + "kW";303 var now = new Date().getHours() + new Date().getMinutes()/60;304 var chargeCompleteAt = "";305 if(data.time_to_full_charge > 0) {306 chargeCompleteAt = (data.time_to_full_charge + now) % 24;307 chargeCompleteAt = parseInt(chargeCompleteAt,10)+":" + zeroFill(parseInt(60*(chargeCompleteAt - parseInt(chargeCompleteAt,10)),10),2);308 }309 if(data.charging_state == 'Charging' || data.charging_state == 'Completed' || data.charging_state == 'Stopped')310 chargeTxt = chargeTxt + " (added "+(parseInt(data.charge_miles_added_ideal*settings.distance_factor*10,10)/10)+" " + settings.distance_unit + ", " + data.charge_energy_added + "kWh, "+ (parseInt(data.charge_energy_added*settings.kwh_cost*100,10)/100) +" "+settings.currency_unit+")\n" +311 chargePowerStr;312 if(data.charging_state == 'Charging')313 chargeTxt = chargeTxt + " (" + data.time_to_full_charge + "h left. At " + data.charge_limit_soc + "% at "+ chargeCompleteAt +")\n";314 return chargeTxt;315}316function makeChargeTxtMini(data) {317 var chargeTxt = data.battery_level + "% " + parseInt(data.ideal_battery_range*settings.distance_factor,10) + settings.distance_unit + " " + data.charging_state+" ";318 return chargeTxt;319}320function getClimateState(actions) {321 console.log("getClimateState(vid="+vehicleID+",nextActions="+actions+")");322 if(climateData) {323 Pebble.showSimpleNotificationOnPebble("Car climate",324 "AC: " + (climateData.is_auto_conditioning_on ? "on @ " + climateData.driver_temp_setting + settings.temperature_unit :"off") + "\n" +325 "In/Outside: " + (climateData.inside_temp ? climateData.inside_temp : "???") + "/" +(climateData.outside_temp ? climateData.outside_temp : "???")+" "+settings.temperature_unit +"\n"326 );327 return;328 }329 var req = new XMLHttpRequest();330 var url = portal+'/api/1/vehicles/'+vehicleID+'/data_request/climate_state';331 req.open('GET', url, true);332 req.setRequestHeader('Authorization','Bearer '+access_token);333 req.onload = function(e) {334 if (req.readyState == 4) {335 console.log("Response (status: "+req.status+"): " + this.responseText);336 if(req.status == 200) {337 try { data = JSON.parse(this.responseText); } catch(err) { return cb(new Error('Data couldnt be parsed. Is it JSON? '+this.responseText)); }338 if (typeof data != "object") return cb(new Error('expecting a JSON object from Tesla Motors cloud service'));339 if(data.response.length !== 0) {340 console.log(data.response.toString());341 theData = data.response;342 climateData = data.response;343 if(!passiveRequest) { // Don't show popup if its not a GUI initiated request.344 Pebble.showSimpleNotificationOnPebble("Car climate",345 "AC: " + (climateData.is_auto_conditioning_on ? "on @ " + climateData.driver_temp_setting + settings.temperature_unit :"off") + "\n" +346 "In/Outside: " + (climateData.inside_temp ? climateData.inside_temp : "???") + "/" +(climateData.outside_temp ? climateData.outside_temp : "???")+ settings.temperature_unit + "\n"347 );348 } 349 if(typeof climateData == "object")350 Pebble.sendAppMessage({ "interiorTemp": climateData.inside_temp + "/" + climateData.outside_temp },connectOkHandler,connectFailHandler);351 performActions(actions); // perform remaining actions352 }353 } else {354 console.log("Failed.\n"+this.getAllResponseHeaders());355 Pebble.sendAppMessage({"99":"Failed!!"});356 }357 }358 };359 req.send(null);360}361function performCommand(action,actions) {362 console.log("cmd: "+action.cmd+"(vid="+vehicleID+")");363 if(typeof action.method == "undefined")364 action.method = 'GET';365 if(action.method == 'POST') {366 chargeData = null; 367 climateData = null;368 }369 var req = new XMLHttpRequest();370 var url = portal +'/api/1/vehicles/'+vehicleID+'/command/'+action.cmd;371 console.log(action.method+" url: "+url);372 req.open(action.method, url, true);373 req.setRequestHeader('Authorization','Bearer '+access_token);374 req.setRequestHeader('User-Agent', 'Model S 2.1.79 (Nexus 5; Android REL 4.4.4; en_US)');375 req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');376 req.setRequestHeader('Accept-Encoding', 'gzip,deflate');377 req.onload = function(e) {378 if (req.readyState == 4) {379 console.log("Response (status: "+req.status+"): " + this.responseText);380 if(req.status == 200) {381 console.log("HTTP GET success.\n");382 try { data = JSON.parse(this.responseText); } catch(err) { return cb(new Error('Data couldnt be parsed. Is it JSON? '+this.responseText)); }383 if (typeof data != "object") return cb(new Error('expecting a JSON object from Tesla Motors cloud service'));384 console.log(data);385 if(data.response === false) {386 Pebble.showSimpleNotificationOnPebble(action.name,387 "Result: " + data.result + "\n" +388 "Reason: " + data.reason389 );390 performActions(actions);391 }392 else {393 if(typeof data.response == 'undefined')394 Pebble.showSimpleNotificationOnPebble(action.name,"HTTP response:\n"+this.responseText);395 else {396 Pebble.showSimpleNotificationOnPebble(action.name,397 "Success! \n" +398 "" + data.response.reason399 );400 }401 performActions(actions); // perform remaining actions402 }403 } else {404 console.log("Failed.\n"+this.getAllResponseHeaders());405 Pebble.sendAppMessage({"99":"Failed!!"});406 }407 }408 };409 req.send(null);410}411function connectOkHandler(e) {412 console.log("Successfully delivered message");413}414function connectFailHandler(e) {415 console.log("Failed delivering message");...
test_breakpoint-24.js
Source:test_breakpoint-24.js
...26 }27 foo();28 //# sourceURL=http://example.com/code.js`29 );30 await performActions(threadFront, [31 [32 "paused at first debugger statement",33 { line: 2, type: "debuggerStatement" },34 "stepOver",35 ],36 [37 "paused at the second debugger statement",38 { line: 3, type: "resumeLimit" },39 "resume",40 ],41 [42 "paused at the third debugger statement",43 { line: 4, type: "debuggerStatement" },44 "resume",45 ],46 ]);47}48// Ensure that we advance to the next line when we hit a breakpoint49// on a line with a debugger statement and resume.50async function testBreakpointsAndDebuggerStatements({51 threadFront,52 targetFront,53}) {54 const consoleFront = await targetFront.getFront("console");55 consoleFront.evaluateJSAsync(56 `function foo(stop) {57 debugger;58 debugger;59 debugger;60 }61 foo();62 //# sourceURL=http://example.com/testBreakpointsAndDebuggerStatements.js`63 );64 threadFront.setBreakpoint(65 {66 sourceUrl: "http://example.com/testBreakpointsAndDebuggerStatements.js",67 line: 3,68 },69 {}70 );71 await performActions(threadFront, [72 [73 "paused at first debugger statement",74 { line: 2, type: "debuggerStatement" },75 "resume",76 ],77 [78 "paused at the breakpoint at the second debugger statement",79 { line: 3, type: "breakpoint" },80 "resume",81 ],82 [83 "pause at the third debugger statement",84 { line: 4, type: "debuggerStatement" },85 "resume",86 ],87 ]);88}89// Ensure that we advance to the next line when we step to90// a line with a breakpoint and resume.91async function testBreakpoints({ threadFront, targetFront }) {92 const consoleFront = await targetFront.getFront("console");93 consoleFront.evaluateJSAsync(94 `function foo(stop) {95 debugger;96 a();97 debugger;98 }99 function a() {}100 foo();101 //# sourceURL=http://example.com/testBreakpoints.js`102 );103 threadFront.setBreakpoint(104 { sourceUrl: "http://example.com/testBreakpoints.js", line: 3, column: 6 },105 {}106 );107 await performActions(threadFront, [108 [109 "paused at first debugger statement",110 { line: 2, type: "debuggerStatement" },111 "stepOver",112 ],113 ["paused at a()", { line: 3, type: "resumeLimit" }, "resume"],114 [115 "pause at the second debugger satement",116 { line: 4, type: "debuggerStatement" },117 "resume",118 ],119 ]);120}121// Ensure that we advance to the next line when we step to122// a line with a breakpoint and resume.123async function testLoops({ threadFront, targetFront }) {124 const consoleFront = await targetFront.getFront("console");125 consoleFront.evaluateJSAsync(126 `function foo(stop) {127 let i = 0;128 debugger;129 while (i++ < 2) {130 debugger;131 }132 debugger;133 }134 foo();135 //# sourceURL=http://example.com/testLoops.js`136 );137 await performActions(threadFront, [138 [139 "paused at first debugger statement",140 { line: 3, type: "debuggerStatement" },141 "resume",142 ],143 [144 "pause at the second debugger satement",145 { line: 5, type: "debuggerStatement" },146 "resume",147 ],148 [149 "pause at the second debugger satement (2nd time)",150 { line: 5, type: "debuggerStatement" },151 "resume",152 ],153 [154 "pause at the third debugger satement",155 { line: 7, type: "debuggerStatement" },156 "resume",157 ],158 ]);159}160async function performActions(threadFront, actions) {161 for (const action of actions) {162 await performAction(threadFront, action);163 }164}165async function performAction(threadFront, [description, result, action]) {166 info(description);167 const packet = await waitForEvent(threadFront, "paused");168 Assert.equal(packet.frame.where.line, result.line);169 Assert.equal(packet.why.type, result.type);170 await threadFront[action]();...
jsonreader.js
Source:jsonreader.js
1const fileSelectorbutton = document.getElementById('json-selector');2const filepath = document.getElementById('filepath');3let currentState= "";4let initialState = "";5let finalState = "";6let workflowObject=new Object();7fileSelectorbutton.addEventListener("click", (event) => {ReadWorkflowdata();readJSON(filepath.value);});8function readJSON(path) { 9 const json= '{ "name":"John", "age":30, "city":"New York"}';10 const fs = require('fs');11 fs.writeFile('workflowdata2.json', json, 'utf8', callback); 12 // var xhr = new XMLHttpRequest(); 13 // console.log('Path is '+path);14 // xhr.open('GET', path, true); 15 // xhr.responseType = 'blob'; 16 // xhr.onload = function(e) { 17 // if (this.status == 200) { 18 // var file = new File([this.response], 'temp'); 19 // var fileReader = new FileReader(); 20 // fileReader.addEventListener('load', function(){ 21 // //do stuff with fileReader.result 22 // const jsonResult= fileReader.result;23 // var obj = JSON.parse(jsonResult);24 // ReadJsonObject(obj);25 // }); 26 // fileReader.readAsText(file); 27 // } 28 // } 29 // xhr.send(); 30} 31function ReadWorkflowdata(){32 //readJSON('worflowdata.json');33}34function ReadJsonObject(obj){35 if (typeof obj.WorkflowData === 'undefined') {36 if(obj.States.indexOf(currentState)!=-1)37 {38 //states are updated39 PerformActions(obj);40 }41 else42 {43 //we are in the first state44 initialState = obj.InitialState;45 currentState = obj.IntialState;46 finalState = obj.FinalState;47 PerformActions(obj);48 }49 console.log(obj)50 }51 else{52 //execute for workflowdata53 currentState = obj.WorkflowData.CurrentState;54 initialState = obj.WorkflowData.InitialState;55 finalState = obj.WorkflowData.FinalState;56 workflowObject= obj;57 58 }59 // for(var index in obj.steps)60 // {61 // console.log(obj.steps[index]);62 // }63 64 // let CurrentStateObj = 65 // {66 // CurrentState:obj.steps[0].ID,67 // Steptype: obj.steps[0].steptype,68 // Description: obj.steps[0].description,69 // Inputs:obj.steps[0].Inputs,70 // NextStepId: obj.steps[0].NextStepId71 // };72 // PerformActions(CurrentStateObj);73 //debugger;74}75function PerformActions(obj){76 for(var state in obj.states){77 if(obj.state.Name==currentState){78 ExecuteAction(obj.state.action)79 SaveTransition(obj.state.target)80 }81 }82 //if(obj.CurrentState === "Complete"){83 // return;84 //}85 //debugger;86 //let status = "approved";87 //UpdateState(obj,status);88}89function ExecuteAction(action){90 switch(action){91 case sendEmail:92 sendEmail(action.InputParameters)93 case saveData:94 saveData(action.InputParameters)95 }96}97function sendEmail(InputParameters){98}99function saveData(InputParameters){100}101function SaveTransition(target){102 currentstate=target;103 UpdateCurrentStateinJson(currentState)104}105function UpdateCurrentStateinJson(currentState)106{107 workflowObject.WorkflowData.CurrentState=currentState;108 var json = Json.stringify(workflowObject);109 const fs = require('fs');110 fs.writeFile('workflowdata2.json', json, 'utf8', callback);111}112function SendEmail(obj,status){113 Email.send({114 Host : "smtp.office365.com",115 Username : username,116 Password : password,117 To : 'Vedantam.Chaitanya@pepsico.com',118 From : "maharshi.choudhury@pepsico.com",119 Subject : "This is the subject",120 Body : "And this is the body"121 }).then(122 message => alert(message)123 );...
PerformActions.test.js
Source:PerformActions.test.js
1/*-2 * ============LICENSE_START=======================================================3 * ONAP CLAMP4 * ================================================================================5 * Copyright (C) 2019 AT&T Intellectual Property. All rights6 * reserved.7 * ================================================================================8 * Licensed under the Apache License, Version 2.0 (the "License");9 * you may not use this file except in compliance with the License.10 * You may obtain a copy of the License at11 *12 * http://www.apache.org/licenses/LICENSE-2.013 *14 * Unless required by applicable law or agreed to in writing, software15 * distributed under the License is distributed on an "AS IS" BASIS,16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.17 * See the License for the specific language governing permissions and18 * limitations under the License.19 * ============LICENSE_END============================================20 * ===================================================================21 *22 */23import React from 'react';24import { shallow } from 'enzyme';25import PerformActions from './PerformActions';26import LoopCache from '../../api/LoopCache';27import LoopActionService from '../../api/LoopActionService';28describe('Verify PerformActions', () => {29 const loopCache = new LoopCache({30 "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca"31 });32 it('Test the render method action failed', async () => {33 const flushPromises = () => new Promise(setImmediate);34 const historyMock = { push: jest.fn() };35 const updateLoopFunction = jest.fn();36 const showSucAlert = jest.fn();37 const showFailAlert = jest.fn();38 const setBusyLoading = jest.fn();39 const clearBusyLoading = jest.fn();40 41 LoopActionService.refreshStatus = jest.fn().mockImplementation(() => {42 return Promise.resolve({43 ok: true,44 status: 200,45 json: () => {}46 });47 });48 const component = shallow(<PerformActions loopCache={loopCache} 49 loopAction="submit" history={historyMock} updateLoopFunction={updateLoopFunction} showSucAlert={showSucAlert} showFailAlert={showFailAlert} setBusyLoading={setBusyLoading} clearBusyLoading={clearBusyLoading}/>)50 await flushPromises();51 component.update();52 expect(historyMock.push.mock.calls[0]).toEqual([ '/']);53 });54 it('Test the render method action successful', async () => {55 const flushPromises = () => new Promise(setImmediate);56 const historyMock = { push: jest.fn() };57 const updateLoopFunction = jest.fn();58 const showSucAlert = jest.fn();59 const showFailAlert = jest.fn();60 const setBusyLoading = jest.fn();61 const clearBusyLoading = jest.fn();62 LoopActionService.performAction = jest.fn().mockImplementation(() => {63 return Promise.resolve({64 ok: true,65 status: 200,66 json: () => {}67 });68 }); 69 LoopActionService.refreshStatus = jest.fn().mockImplementation(() => {70 return Promise.resolve({71 ok: true,72 status: 200,73 json: () => {}74 });75 });76 const component = shallow(<PerformActions loopCache={loopCache} 77 loopAction="submit" history={historyMock} updateLoopFunction={updateLoopFunction} showSucAlert={showSucAlert} showFailAlert={showFailAlert} setBusyLoading={setBusyLoading} clearBusyLoading={clearBusyLoading}/>)78 await flushPromises();79 component.update();80 expect(historyMock.push.mock.calls[0]).toEqual([ '/']);81 });...
test.js
Source:test.js
...45 actions(10)46 .onSuccess(function(value) {47 var execTime = Math.floor((new Date()).valueOf() - startTime);48 console.log( "+" + value + " /" + execTime );49 if ( --iterations > 0 ) performActions();50 else console.log( "DONE" );51 })52 .onFailure(function(value) {53 var execTime = Math.floor((new Date()).valueOf() - startTime);54 console.log( value + " /" + execTime );55 if ( --iterations > 0 ) performActions();56 else console.log( "DONE" );57 });58};
...
actions.js
Source:actions.js
1$(document).ready(function(){2 $('button#boot').click(function() {3 var l = Ladda.create( document.querySelector( '#boot' ) );4 l.start();5 $.get('/performActions.php?theAction=boot', function(data) {6 l.stop();7 $("#actionResults").show(0).delay(8000).hide(0);8 $("#bootResult").show(0).delay(7777).hide(0);9 });10 return false;11 });12 $('button#reboot').click(function() { 13 var l = Ladda.create( document.querySelector( '#reboot' ) );14 l.start();15 $.get('/performActions.php?theAction=reboot', function(data) {16 l.stop();17 $("#actionResults").show(0).delay(8000).hide(0);18 $("#rebootResult").show(0).delay(7777).hide(0);19 });20 return false;21 });22 $('button#shutdown').click(function() {23 var l = Ladda.create( document.querySelector( '#shutdown' ) );24 l.start();25 $.get('/performActions.php?theAction=shutdown', function(data) {26 l.stop();27 $("#actionResults").show(0).delay(8000).hide(0);28 $("#shutdownResult").show(0).delay(7777).hide(0);29 });30 return false;31 });...
releaseActions.js
Source:releaseActions.js
2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.default = performActions;...
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = { desiredCapabilities: { browserName: 'chrome' } };3var client = webdriverio.remote(options);4 .init()5 .setValue('#lst-ib', 'WebdriverIO')6 .click('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)')7 .getTitle().then(function(title) {8 console.log('Title was: ' + title);9 })10 .end();
Using AI Code Generation
1const webdriverio = require('webdriverio');2const options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .pause(5000)9 .performActions([10 {11 parameters: { pointerType: 'mouse' },12 { type: 'pointerMove', duration: 0, x: 200, y: 200 },13 { type: 'pointerDown', button: 0 },14 { type: 'pause', duration: 1000 },15 { type: 'pointerUp', button: 0 }16 }17 .end();
Using AI Code Generation
1const webdriverio = require('webdriverio');2const options = {3 desiredCapabilities: {4 }5};6const client = webdriverio.remote(options);7 .init()8 .performActions([{9 "options": {10 }11 }, {12 "options": {13 }14 }, {15 "options": {16 }17 }, {18 }])19 .pause(2000)20 .end();
Using AI Code Generation
1describe('Performing Actions', () => {2 it('should drag and drop', () => {3 const source = $('#draggable')4 const target = $('#droppable')5 source.dragAndDrop(target)6 browser.pause(3000)7 })8})9describe('Performing Actions', () => {10 it('should drag and drop', () => {11 const source = $('#draggable')12 const target = $('#droppable')13 browser.performActions([{14 parameters: { pointerType: 'mouse' },15 { type: 'pointerMove', duration: 0, x: source.getLocation('x'), y: source.getLocation('y') },16 { type: 'pointerDown', button: 0 },17 { type: 'pause', duration: 500 },18 { type: 'pointerMove', duration: 1000, origin: 'pointer', x: 0, y: -100 },19 { type: 'pointerUp', button: 0 }20 }])21 browser.releaseActions()22 browser.pause(3000)23 })24})25describe('Performing Actions', () => {26 it('should drag and drop', () => {27 const source = $('#draggable')28 const target = $('#droppable')29 browser.performActions([{30 parameters: { pointerType: 'mouse' },31 { type: 'pointerMove', duration: 0, x: source.getLocation('x'), y: source.getLocation('y') },32 { type: 'pointerDown', button: 0 },33 { type: 'pause', duration: 500 },34 { type: 'pointerMove', duration: 1000, origin: 'pointer', x: 0, y: -100 },35 { type: 'pointerUp', button: 0 }
Using AI Code Generation
1describe('Drag and Drop', function () {2 it('Drag and Drop', function () {3 browser.switchToFrame(0);4 var source = $('#draggable');5 var target = $('#droppable');6 browser.pause(10000);7 source.dragAndDrop(target);8 browser.pause(10000);9 })10})
Using AI Code Generation
1describe('Performing Actions', () => {2 it('should drag and drop', () => {3 browser.switchToFrame(0);4 const source = $('#draggable');5 const target = $('#droppable');6 source.dragAndDrop(target);7 });8});9describe('Performing Actions', () => {10 it('should drag and drop', () => {11 browser.switchToFrame(0);12 const source = $('#draggable');13 const target = $('#droppable');14 source.dragAndDrop(target);15 });16});17describe('Performing Actions', () => {18 it('should drag and drop', () => {19 browser.switchToFrame(0);20 const source = $('#draggable');21 const target = $('#droppable');22 source.dragAndDrop(target);23 });24});25describe('Performing Actions', () => {26 it('should drag and drop', () => {27 browser.switchToFrame(0);28 const source = $('#draggable');29 const target = $('#droppable');30 source.dragAndDrop(target);31 });32});33describe('Performing Actions', () => {34 it('should drag and drop', () => {35 browser.switchToFrame(0);36 const source = $('#draggable');37 const target = $('#droppable');38 source.dragAndDrop(target);39 });40});41describe('Performing Actions', () => {42 it('should drag and drop', () => {43 browser.switchToFrame(0);44 const source = $('#draggable');45 const target = $('#droppable');
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = { desiredCapabilities: { browserName: 'chrome' } };3var client = webdriverio.remote(options);4 .init()5 .performActions([6 {7 parameters: { pointerType: 'touch' },8 { type: 'pointerMove', duration: 0, x: 100, y: 100 },9 { type: 'pointerDown', button: 0 },10 { type: 'pause', duration: 1000 },11 { type: 'pointerUp', button: 0 },12 },13 {14 parameters: { pointerType: 'touch' },15 { type: 'pointerMove', duration: 0, x: 200, y: 200 },16 { type: 'pointerDown', button: 0 },17 { type: 'pause', duration: 1000 },18 { type: 'pointerUp', button: 0 },19 },20 .pause(3000)21 .end();
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = { desiredCapabilities: { browserName: 'chrome' } };3var client = webdriverio.remote(options);4 .init()5 .getTitle().then(function(title) {6 console.log('Title was: ' + title);7 })8 .setValue('#lst-ib', 'webdriverio')9 .click('#tsbb')10 .getTitle().then(function(title) {11 console.log('Title is: ' + title);12 })13 .pause(1000)14 .end();
Using AI Code Generation
1describe('performActions', () => {2 it('should perform actions', () => {3 const element = $('#get-started')4 element.performActions([5 { type: 'key', id: 'keyboard', actions: [{ type: 'keyDown', value: 'Shift' }] },6 { type: 'pointer', id: 'pointer1', parameters: { pointerType: 'mouse' }, actions: [{ type: 'pointerMove', duration: 0, x: 100, y: 100 }, { type: 'pointerDown', button: 0 }, { type: 'pointerUp', button: 0 }] },7 { type: 'key', id: 'keyboard', actions: [{ type: 'keyUp', value: 'Shift' }] }8 })9})10describe('releaseActions', () => {11 it('should release actions', () => {12 const element = $('#get-started')13 element.performActions([14 { type: 'key', id: 'keyboard', actions: [{ type: 'keyDown', value: 'Shift' }] },15 { type: 'pointer', id: 'pointer1', parameters: { pointerType: 'mouse' }, actions: [{ type: 'pointerMove', duration: 0, x: 100, y: 100 }, { type: 'pointerDown', button: 0 }, { type: 'pointerUp', button: 0 }] },16 { type: 'key', id: 'keyboard', actions: [{ type: 'keyUp', value: 'Shift' }] }17 browser.releaseActions()18 })19})20describe('saveScreenshot', () => {21 it('should save screenshot', () => {22 const element = $('#get-started')
Wondering what could be a next-gen browser and mobile test automation framework that is also simple and concise? Yes, that’s right, it's WebdriverIO. Since the setup is very easy to follow compared to Selenium testing configuration, you can configure the features manually thereby being the center of attraction for automation testing. Therefore the testers adopt WedriverIO to fulfill their needs of browser testing.
Learn to run automation testing with WebdriverIO tutorial. Go from a beginner to a professional automation test expert with LambdaTest WebdriverIO tutorial.
Running Your First Automation Script - Learn the steps involved to execute your first Test Automation Script using WebdriverIO since the setup is very easy to follow and the features can be configured manually.
Selenium Automation With WebdriverIO - Read more about automation testing with WebdriverIO and how it supports both browsers and mobile devices.
Browser Commands For Selenium Testing - Understand more about the barriers faced while working on your Selenium Automation Scripts in WebdriverIO, the ‘browser’ object and how to use them?
Handling Alerts & Overlay In Selenium - Learn different types of alerts faced during automation, how to handle these alerts and pops and also overlay modal in WebdriverIO.
How To Use Selenium Locators? - Understand how Webdriver uses selenium locators in a most unique way since having to choose web elements very carefully for script execution is very important to get stable test results.
Deep Selectors In Selenium WebdriverIO - The most popular automation testing framework that is extensively adopted by all the testers at a global level is WebdriverIO. Learn how you can use Deep Selectors in Selenium WebdriverIO.
Handling Dropdown In Selenium - Learn more about handling dropdowns and how it's important while performing automated browser testing.
Automated Monkey Testing with Selenium & WebdriverIO - Understand how you can leverage the amazing quality of WebdriverIO along with selenium framework to automate monkey testing of your website or web applications.
JavaScript Testing with Selenium and WebdriverIO - Speed up your Javascript testing with Selenium and WebdriverIO.
Cross Browser Testing With WebdriverIO - Learn more with this step-by-step tutorial about WebdriverIO framework and how cross-browser testing is done with WebdriverIO.
Get 100 minutes of automation test minutes FREE!!