Best JavaScript code snippet using appium-base-driver
command_runner.js
Source:command_runner.js
1import {2 regExpMatch,3 replaceAllFields,4 traverseJson,5 filterJson,6 setLocalStorage,7 getLocalStorage,8 setSessionStorage,9 getSessionStorage10} from '@replayweb/utils'11import { expect } from 'chai'12import {13 getAndWaitForElement,14 getExecElString,15 getSelector,16 fetchTable17} from './utilities'18import deepEqual from 'deep-equal'19/**20 * Logs message to the console when verbose21 * @private22 * @param {Object} Command - The command object to run23 * @param {string} Command.command - The command to execute24 * @param {string} Command.parameters - The parameters for the command25 * @param {Object} context - An object for static string replacements26 * @returns {Promise} - A promise chain of webdriverio commands27 */28export async function runCommand(29 { command, parameters },30 context,31 implicitWait,32 hooks33) {34 const finalParameters = await replaceAllFields(parameters, context)35 await hooks.beforeCommand.promise(36 { command, parameters: finalParameters },37 context,38 browser39 )40 switch (command) {41 case 'assertAttribute': {42 const { target, attribute, expected } = finalParameters43 return getAndWaitForElement(44 target,45 implicitWait,46 { command, parameters: finalParameters },47 context,48 hooks49 )50 .then(el => el.getAttribute(attribute))51 .then(attributeValue => {52 const re = expected.match(/^\/.+\/$/)53 ? regExpMatch(expected, attributeValue)54 : expected55 return expect(attributeValue).to.equal(re)56 })57 }58 case 'assertCheckboxState': {59 const { target, expected } = finalParameters60 return getAndWaitForElement(61 target,62 implicitWait,63 { command, parameters: finalParameters },64 context,65 hooks66 ).then(el => {67 return Promise.all([68 el.getAttribute('type'),69 el.getAttribute('checked')70 ]).then(([type, checked]) => {71 return expect(72 type === 'checkbox' && Boolean(checked) === Boolean(expected)73 ).to.equal(true)74 })75 })76 }77 case 'assertClassDoesNotExist': {78 const { target, class: assertClass } = finalParameters79 return getAndWaitForElement(80 target,81 implicitWait,82 { command, parameters: finalParameters },83 context,84 hooks85 )86 .then(el => el.getAttribute('class'))87 .then(classes => expect(classes.split(' ')).to.not.include(assertClass))88 }89 case 'assertClassExists': {90 const { target, class: assertClass } = finalParameters91 return getAndWaitForElement(92 target,93 implicitWait,94 { command, parameters: finalParameters },95 context,96 hooks97 )98 .then(el => el.getAttribute('class'))99 .then(classes => expect(classes.split(' ')).to.include(assertClass))100 }101 case 'assertElementPresent': {102 const { target, timeout } = finalParameters103 return browser104 .$(getSelector(target))105 .then(el => el.waitForExist(parseInt(timeout) || implicitWait))106 }107 case 'assertElementNotPresent': {108 const { target, timeout } = finalParameters109 return browser110 .$(getSelector(target))111 .then(el => el.waitForExist(parseInt(timeout) || implicitWait, true))112 }113 case 'assertElementVisible': {114 const { target, timeout } = finalParameters115 return browser116 .$(getSelector(target))117 .then(el => el.waitForDisplayed(parseInt(timeout) || implicitWait))118 }119 case 'assertElementNotVisible': {120 const { target, timeout } = finalParameters121 return browser122 .$(getSelector(target))123 .then(el =>124 el.waitForDisplayed(parseInt(timeout) || implicitWait, true)125 )126 }127 case 'assertLocalStorage': {128 const { key, expected } = finalParameters129 return browser130 .execute(getLocalStorage, key)131 .then(value => expect(value).to.equal(expected))132 }133 case 'assertSessionStorage': {134 const { key, expected } = finalParameters135 return browser136 .execute(getSessionStorage, key)137 .then(value => expect(value).to.equal(expected))138 }139 case 'assertStyle': {140 const { target, property, expected } = finalParameters141 /*142 * using browser.execute for consistency between the extension and testrunner143 * browser.getCssProperty returns some styles in a different format144 * getComputedProperty for 'color' => rgb(X, X, X)145 * getCssProperty for 'color' => rgba(X, X, X, X)146 */147 // if the selector strategy is id, replace it with identifier to get an id in the form #someid so it works in queryselector148 const newTarget =149 target.indexOf('id=') === 0150 ? target.replace('id=', 'identifier=')151 : target152 const execString = `return window.getComputedStyle(document.querySelector(\`${getSelector(153 newTarget154 )}\`))['${property}']`155 return getAndWaitForElement(156 target,157 implicitWait,158 { command, parameters: finalParameters },159 context,160 hooks161 )162 .then(el => browser.execute(execString))163 .then(computed => {164 if (computed === undefined) {165 return Promise.reject(166 new Error(`style '${property}' not found on element ${target}`)167 )168 }169 return expect(computed).to.equal(expected)170 })171 }172 case 'assertTableNotEmpty': {173 const { target } = finalParameters174 return fetchTable(target).then(table =>175 expect(table).to.have.length.of.at.least(1)176 )177 }178 case 'assertText': {179 const { target, expected = '' } = finalParameters180 return getAndWaitForElement(181 target,182 implicitWait,183 { command, parameters: finalParameters },184 context,185 hooks186 ).then(el =>187 Promise.all([el.getText(), el.getValue()]).then(([text, value]) => {188 const data = text !== '' ? text : value || ''189 const re = expected.match(/^\/.+\/$/)190 ? regExpMatch(expected, data)191 : expected192 return expect(data).to.equal(re)193 })194 )195 }196 case 'assertTitle': {197 const { expected } = finalParameters198 return browser.getTitle().then(title => expect(title).to.equal(expected))199 }200 case 'assertUrl': {201 const { expected } = finalParameters202 return browser.getUrl().then(url => expect(url).to.equal(expected))203 }204 case 'assertJsonInContext': {205 const { key, expected } = finalParameters206 return expect(deepEqual(context[key], expected)).to.equal(true)207 }208 // END ASSERTS209 // *************************************************************************210 case 'captureScreenshot': {211 return browser.takeScreenshot()212 }213 case 'clearValue': {214 const { target } = finalParameters215 return getAndWaitForElement(216 target,217 implicitWait,218 { command, parameters: finalParameters },219 context,220 hooks221 ).then(el => el.clearValue())222 }223 case 'click':224 case 'clickAndWait': {225 const { target } = finalParameters226 getSelector(target)227 return getAndWaitForElement(228 target,229 implicitWait,230 { command, parameters: finalParameters },231 context,232 hooks233 ).then(el => el.click())234 }235 case 'comment': {236 return Promise.resolve(true)237 }238 case 'debug': {239 return browser.debug()240 }241 case 'deleteAllCookies':242 return browser.deleteCookies()243 case 'dragAndDropToObject': {244 const { startTarget, endTarget } = finalParameters245 return Promise.all([246 getAndWaitForElement(247 startTarget,248 implicitWait,249 { command, parameters: finalParameters },250 context251 ),252 hooks,253 getAndWaitForElement(254 endTarget,255 implicitWait,256 { command, parameters: finalParameters },257 context,258 hooks259 )260 ]).then(([el, _]) => el.dragAndDrop(getSelector(endTarget)))261 }262 case 'http': {263 const { url, method = 'GET', body, headers = {}, key } = finalParameters264 return fetch(url, {265 method,266 body: body ? JSON.stringify(body) : undefined,267 headers: new Headers(headers)268 })269 .then(res => {270 if (parseInt(res.status) >= 300) {271 return Promise.reject(272 new Error(273 `Error in ${method} call to ${url}:\nResponse code was ${res.status}`274 )275 )276 }277 return res.json()278 })279 .then(value => {280 context[key] = value281 })282 }283 case 'mouseOver': {284 const { target } = finalParameters285 return getAndWaitForElement(286 target,287 implicitWait,288 { command, parameters: finalParameters },289 context,290 hooks291 ).then(el => el.moveTo())292 }293 case 'mouseEvent': {294 const { target } = finalParameters295 const sel = getSelector(target)296 return ['mouseover', 'mousedown', 'mouseup', 'click']297 .reduce(298 (acc, cv) =>299 acc.then(() =>300 browser.execute(301 getExecElString(sel) +302 '.dispatchEvent(new MouseEvent("' +303 cv +304 '", { bubbles: true }))'305 )306 ),307 getAndWaitForElement(308 target,309 implicitWait,310 { command, parameters: finalParameters },311 context,312 hooks313 )314 )315 .catch(e => {316 if (317 !e.message.includes("Cannot read property 'dispatchEvent' of null")318 ) {319 throw e320 }321 })322 }323 case 'open': {324 const { url } = finalParameters325 return browser.url(url).then(() => browser.pause(2000))326 }327 case 'pause': {328 const { millis } = finalParameters329 const time = isNaN(parseInt(millis)) ? 3000 : parseInt(millis)330 return browser.pause(time)331 }332 case 'refresh': {333 return browser.refresh()334 }335 case 'select': {336 const { target, value } = finalParameters337 const text = value.replace(/^label=/, '')338 return getAndWaitForElement(339 target,340 implicitWait,341 { command, parameters: finalParameters },342 context,343 hooks344 ).then(el => el.selectByVisibleText(text))345 }346 case 'selectAndWait': {347 const { target, value } = finalParameters348 const text = value.replace(/^label=/, '')349 return getAndWaitForElement(350 target,351 implicitWait,352 { command, parameters: finalParameters },353 context,354 hooks355 )356 .then(el => el.selectByVisibleText(text))357 .then(() => browser.pause(3000))358 }359 case 'selectFrame': {360 const { target } = finalParameters361 const sel = getSelector(target)362 if (target.split('=')[0] === 'index') {363 return browser.switchToFrame(parseInt(sel))364 } else if (target.split('=')[0] === 'relative') {365 // use null so webdriverio will select the main DOM366 return browser.switchToFrame(null)367 } else {368 return browser369 .$(getSelector(target))370 .then(el => browser.switchToFrame(el))371 }372 }373 case 'setContext': {374 const { key, value } = finalParameters375 return new Promise((resolve, reject) => {376 context[key] = value377 resolve(true)378 })379 }380 case 'setCookie': {381 const { name, value, domain = '.example.com' } = finalParameters382 return browser.setCookies({ name, value, domain })383 }384 case 'setEnvironment': {385 return new Promise((resolve, reject) => {386 Object.keys(finalParameters).forEach(key => {387 context[key] = finalParameters[key]388 })389 resolve(true)390 })391 }392 case 'setLocalStorage': {393 const { key, value } = finalParameters394 return browser.execute(setLocalStorage, key, value)395 }396 case 'setSession': {397 const { key, value } = finalParameters398 return browser399 .execute(setSessionStorage, key, value)400 .then(() => browser.refresh())401 }402 case 'storeValue': {403 const { target, key } = finalParameters404 return getAndWaitForElement(405 target,406 implicitWait,407 { command, parameters: finalParameters },408 context,409 hooks410 ).then(el =>411 Promise.all([el.getText(), el.getValue()]).then(([text, value]) => {412 const data = text !== '' ? text : value || ''413 context[key] = data414 })415 )416 }417 case 'type': {418 const { target, value } = finalParameters419 return getAndWaitForElement(420 target,421 implicitWait,422 { command, parameters: finalParameters },423 context,424 hooks425 ).then(el => el.setValue(value))426 }427 case 'filterJsonInContext': {428 const { key, resultKey } = finalParameters429 let { locateNode = [], deleteNodes = [] } = finalParameters430 // convert objects to arrays431 locateNode = Object.values(locateNode) // locateNode is a property chain432 deleteNodes = Object.values(deleteNodes).map(nodesToIgnore => {433 // deleteNodes is a list of property chains434 return Object.values(nodesToIgnore)435 })436 const traverseResult = traverseJson(context[key], locateNode)437 const filterResult = filterJson(traverseResult, deleteNodes)438 context[resultKey] = filterResult439 break440 }441 default: {442 throw new Error(443 `Command "${command}" not supported yet. Do you need to update @replayweb/testrunner?`444 )445 }446 }...
implicit-wait-ide.js
Source:implicit-wait-ide.js
1/*2 * Copyright 2012 Florent Breheret3 * http://code.google.com/p/selenium-implicit-wait/4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16 17function ImplicitWait(editor) {18 var self=this;19 this.isRequesting = false;20 this.isWaiting = false;21 this.editor = editor;22 this.buttonHouglassChecked = false;23 this.isImplicitWaitLocatorActivated = false;24 this.isImplicitWaitAjaxActivated = false;25 this.implicitAjaxWait_Condition=null;26 this.implicitAjaxWait_Function=function(){ return true;};27 this.locatorTimeout=0;28 this.conditionTimeout=0;29 this.isLogEnabled=true;30 editor.app.addObserver({31 testSuiteChanged: function(testSuite) {32 if (!self.editor.selDebugger.isHooked) {33 self.editor.selDebugger.isHooked = self.HookAnObjectMethodAfter(self.editor.selDebugger, 'init', self, self.editor_selDebugger_init_hooked);34 }35 }36 });37 self.HookAnObjectMethodBefore(Editor.controller, 'doCommand', self, self.Editor_controller_doCommand_hooked);38}39ImplicitWait.prototype.Editor_controller_doCommand_hooked = function( object, arguments ) {40 switch (arguments[0]) {41 case "cmd_selenium_play":42 case "cmd_selenium_play_suite":43 case "cmd_selenium_reload":44 this.locatorTimeout=this.editor.getOptions().timeout;45 this.isImplicitWaitLocatorActivated = this.buttonHouglassChecked;46 this.isImplicitWaitAjaxActivated = false;47 break;48 }49 return true;50};51ImplicitWait.prototype.editor_selDebugger_init_hooked = function( object, arguments, retvalue ) {52 object.runner.LOG.debug('Implicit wait installation');53 object.runner.IDETestLoop.prototype.resume = Function_Override_TestLoop_resume;54 object.runner.PageBot.prototype.findElement = Function_Override_BrowserBot_findElement;55 this.HookAnObjectMethodBefore(object.runner.LOG, 'log', this, function(){return this.isLogEnabled} );56};57ImplicitWait.prototype.toggleImplicitWaitButton = function(button) {58 button.checked = !button.checked;59 this.buttonHouglassChecked = button.checked;60 this.isImplicitWaitLocatorActivated = this.buttonHouglassChecked;61};62var Function_Override_BrowserBot_findElement = function (locator, win){63 var element = this.findElementOrNull(locator, win);64 if (element == null) {65 throw {66 isFindElementError: true,67 message: "Element " + locator + " not found"68 }69 }70 return core.firefox.unwrap(element);71};72var Function_Override_TestLoop_resume = function() {73 alert(this.currentCommand.name);74 try {75 var self=this;76 if(this.abord) return;77 if(editor.selDebugger.state == Debugger.PAUSE_REQUESTED){78 return this.continueTestAtCurrentCommand();79 }80 if (editor.implicitwait.isImplicitWaitAjaxActivated && !this.currentCommand.implicitElementWait_EndTime) {81 if( !this.currentCommand.implicitAjaxWait_EndTime ){82 this.currentCommand.implicitAjaxWait_EndTime = ( new Date().getTime() + parseInt(editor.implicitwait.conditionTimeout * 0.8) ) ;83 return window.setTimeout( function(){return self.resume.apply(self);}, 3);84 }85 if (new Date().getTime() > this.currentCommand.implicitAjaxWait_EndTime) {86 throw new SeleniumError("Implicit wait timeout reached while waiting for condition \"" + editor.implicitwait.implicitAjaxWait_Condition + "\"");87 }else{88 try{89 ret = editor.implicitwait.implicitAjaxWait_Function.call(editor.selDebugger.runner.selenium);90 //ret=eval(editor.implicitwait.implicitAjaxWait_Condition);91 //ret=(function(condition){return eval(condition);}).call(editor.selDebugger.runner.selenium, editor.implicitwait.implicitAjaxWait_Condition)92 } catch (e) {93 throw new SeleniumError("ImplicitWaitCondition failed : " + e.message );94 }95 if(!ret) return window.setTimeout( function(){return self.resume.apply(self);}, 20);96 }97 }98 if(editor.implicitwait.isImplicitWaitLocatorActivated){99 if(!this.currentCommand.implicitElementWait_EndTime){100 this.currentCommand.implicitElementWait_EndTime = ( new Date().getTime() + parseInt(editor.implicitwait.locatorTimeout * 0.8) ) ;101 }102 }103 editor.selDebugger.runner.selenium.browserbot.runScheduledPollers();104 this._executeCurrentCommand();105 this.continueTestWhenConditionIsTrue();106 } catch (e) {107 if(e.isFindElementError || e.haminiumStage){108 if(editor.implicitwait.isImplicitWaitLocatorActivated){109 if( new Date().getTime() < this.currentCommand.implicitElementWait_EndTime){110 editor.implicitwait.isLogEnabled = false;111 return window.setTimeout( function(){return self.resume.apply(self);}, 20);112 }else{113 e = SeleniumError( "Implicit wait timeout reached. " + e.message );114 }115 }else{116 e = SeleniumError( e.message );117 }118 }119 editor.implicitwait.isLogEnabled = true;120 if(!this._handleCommandError(e)){121 this.testComplete();122 }else {123 this.continueTest();124 }125 }126 editor.implicitwait.isLogEnabled = true;127};128ImplicitWait.prototype.HookAnObjectMethodBefore = function(ClassObject, ClassMethod, HookClassObject, HookMethod) {129 if (ClassObject) {130 var method_id = ClassMethod.toString() + HookMethod.toString();131 if (!ClassObject[method_id]) {132 ClassObject[method_id] = ClassObject[ClassMethod];133 ClassObject[ClassMethod] = function() {134 if( HookMethod.call(HookClassObject, ClassObject, arguments )==true ){135 return ClassObject[method_id].apply(ClassObject, arguments);136 }137 }138 return true;139 }140 }141 return false;142};143ImplicitWait.prototype.HookAnObjectMethodAfter = function(ClassObject, ClassMethod, HookClassObject, HookMethod) {144 if (ClassObject) {145 var method_id = ClassMethod.toString() + HookMethod.toString();146 if (!ClassObject[method_id]) {147 ClassObject[method_id] = ClassObject[ClassMethod];148 ClassObject[ClassMethod] = function() {149 var retvalue = ClassObject[method_id].apply(ClassObject, arguments);150 return HookMethod.call(HookClassObject, ClassObject, arguments, retvalue );151 }152 return true;153 }154 }155 return false;156};157try {158 this.editor.implicitwait = new ImplicitWait(this.editor);159} catch (error) {160 alert('Error in ImplicitWait: ' + error);...
user-extensions.js
Source:user-extensions.js
1/**2 * @Author : Florent BREHERET3 * @Function : Activate an implicite wait on action commands when trying to find elements.4 * @Param timeout : Timeout in millisecond, set 0 to disable the implicit wait5 * @Exemple 1 : setImplicitWaitLocator | 06 * @Exemple 1 : setImplicitWaitLocator | 10007 */8Selenium.prototype.doSetImplicitWaitLocator = function(timeout){9 if( timeout== 0 ) {10 implicitwait.locatorTimeout=0;11 implicitwait.isImplicitWaitLocatorActivated=false;12 }else{13 implicitwait.locatorTimeout=parseInt(timeout);14 implicitwait.isImplicitWaitLocatorActivated=true;15 }16};17/**18 * @author : Florent BREHERET19 * @Function : Activate an implicite wait for condition before commands are executed.20 * @Param timeout : Timeout in millisecond, set 0 to disable the implicit wait21 * @Param condition_js : Javascript logical expression that need to be true to execute each command.22 *23 * @Exemple 0 : setImplicitWaitCondition | 0 | 24 * @Exemple 1 : setImplicitWaitCondition | 1000 | (typeof window.Sys=='undefined') ? true : window.Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()==false;25 * @Exemple 2 : setImplicitWaitCondition | 1000 | (typeof window.dojo=='undefined') ? true : window.dojo.io.XMLHTTPTransport.inFlight.length==0;26 * @Exemple 3 : setImplicitWaitCondition | 1000 | (typeof window.Ajax=='undefined') ? true : window.Ajax.activeRequestCount==0;27 * @Exemple 4 : setImplicitWaitCondition | 1000 | (typeof window.tapestry=='undefined') ? true : window.tapestry.isServingRequests()==false;28 * @Exemple 4 : setImplicitWaitCondition | 1000 | (typeof window.jQuery=='undefined') ? true : window.jQuery.active==0;29 */30Selenium.prototype.doSetImplicitWaitCondition = function( timeout, condition_js ) {31 if( timeout==0 ) {32 implicitwait.conditionTimeout=0;33 implicitwait.implicitAjaxWait_Condition=null;34 implicitwait.isImplicitWaitAjaxActivated=false;35 }else{36 implicitwait.conditionTimeout=parseInt(timeout);37 implicitwait.implicitAjaxWait_Condition=condition_js;38 implicitwait.isImplicitWaitAjaxActivated=true;39 }40}41function ImplicitWait() {42 var self=this;43 this.isImplicitWaitLocatorActivated = false;44 this.isImplicitWaitAjaxActivated = false;45 this.implicitAjaxWait_Condition=null;46 this.conditionTimeout=0;47 this.locatorTimeout=0;48 this.isLogEnabled=true;49}50MozillaBrowserBot.prototype.findElement = function (locator, win){51 var element = this.findElementOrNull(locator, win);52 if (element == null) {53 throw {54 isFindElementError: true,55 message: "Element " + locator + " not found"56 }57 }58 return core.firefox.unwrap(element);59};60KonquerorBrowserBot.prototype.findElement = MozillaBrowserBot.prototype.findElement;61SafariBrowserBot.prototype.findElement = MozillaBrowserBot.prototype.findElement;62OperaBrowserBot.prototype.findElement = MozillaBrowserBot.prototype.findElement;63IEBrowserBot.prototype.findElement = MozillaBrowserBot.prototype.findElement;64ImplicitWait.resume_overrided = function() {65 try {66 var self=this;67 if(this.abord) return;68 if( !typeof htmlTestRunner === 'undefined'){69 if(htmlTestRunner.controlPanel.runInterval == -1){70 return this.continueTestAtCurrentCommand();71 }72 }73 if (implicitwait.isImplicitWaitAjaxActivated && !this.currentCommand.implicitElementWait_EndTime) {74 if( !this.currentCommand.implicitAjaxWait_EndTime ){75 this.currentCommand.implicitAjaxWait_EndTime = (new Date().getTime() + parseInt(implicitwait.conditionTimeout * 0.8));76 return window.setTimeout( function(){return self.resume.apply(self);}, 3);77 }78 if (new Date().getTime() > this.currentCommand.implicitAjaxWait_EndTime) {79 throw new SeleniumError("Implicit wait timeout reached while waiting for condition \"" + implicitwait.implicitAjaxWait_Condition + "\"");80 }else{81 var ret;82 try{83 ret=eval(implicitwait.implicitAjaxWait_Condition);84 //ret = implicitwait.implicitAjaxWait_Function.call(htmlTestRunner.selDebugger.runner.selenium);85 //ret=(function(condition){return eval(condition);}).call(htmlTestRunner.selDebugger.runner.selenium, implicitwait.implicitAjaxWait_Condition)86 } catch (e) {87 throw new SeleniumError("ImplicitWaitCondition failed : " + e.message );88 }89 if(!ret) return window.setTimeout( function(){return self.resume.apply(self);}, 20);90 }91 }92 if(implicitwait.isImplicitWaitLocatorActivated){93 if(!this.currentCommand.implicitElementWait_EndTime){94 this.currentCommand.implicitElementWait_EndTime = (new Date().getTime() + parseInt(implicitwait.locatorTimeout * 0.8));95 }96 }97 selenium.browserbot.runScheduledPollers();98 this._executeCurrentCommand();99 this.continueTestWhenConditionIsTrue();100 } catch (e) {101 if(e.isFindElementError){102 if(implicitwait.isImplicitWaitLocatorActivated){103 if( new Date().getTime() < this.currentCommand.implicitElementWait_EndTime){104 implicitwait.isLogEnabled = false;105 return window.setTimeout( function(){return self.resume.apply(self);}, 20);106 }else{107 e = SeleniumError( "Implicit wait timeout reached. " + e.message );108 }109 }else{110 e = SeleniumError( e.message );111 }112 }113 implicitwait.isLogEnabled = true;114 if(!this._handleCommandError(e)){115 this.testComplete();116 }else {117 this.continueTest();118 }119 }120 implicitwait.isLogEnabled = true;121};122ImplicitWait.HookAnObjectMethodBefore = function(ClassObject, ClassMethod, HookClassObject, HookMethod) {123 if (ClassObject) {124 var method_id = ClassMethod.toString() + HookMethod.toString();125 if (!ClassObject[method_id]) {126 ClassObject[method_id] = ClassObject[ClassMethod];127 ClassObject[ClassMethod] = function() {128 if( HookMethod.call(HookClassObject, ClassObject, arguments )==true ){129 return ClassObject[method_id].apply(ClassObject, arguments);130 }131 }132 return true;133 }134 }135 return false;136};137try {138 var implicitwait = new ImplicitWait();139 ImplicitWait.HookAnObjectMethodBefore(LOG, 'log', implicitwait, function(){return implicitwait.isLogEnabled} );140 if( typeof RemoteRunner == 'function'){141 RemoteRunner.prototype.resume = ImplicitWait.resume_overrided;142 }143 if( typeof HtmlRunnerTestLoop == 'function'){144 HtmlRunnerTestLoop.prototype.resume = ImplicitWait.resume_overrided;145 }146} catch (error) {147 alert('Error in ImplicitWait: ' + error);...
timeout-specs.js
Source:timeout-specs.js
...64 });65 });66 describe('implicitWait', function () {67 it('should call setImplicitWait when given an integer', async function () {68 await driver.implicitWait(42);69 implicitWaitSpy.calledOnce.should.be.true;70 implicitWaitSpy.firstCall.args[0].should.equal(42);71 driver.implicitWaitMs.should.eql(42);72 });73 it('should call setImplicitWait when given a string', async function () {74 await driver.implicitWait('42');75 implicitWaitSpy.calledOnce.should.be.true;76 implicitWaitSpy.firstCall.args[0].should.equal(42);77 driver.implicitWaitMs.should.eql(42);78 });79 it('should throw an error if something random is sent', async function () {80 await driver.implicitWait('howdy').should.eventually.be.rejected;81 });82 it('should throw an error if timeout is negative', async function () {83 await driver.implicitWait(-42).should.eventually.be.rejected;84 });85 });86 describe('set implicit wait', function () {87 it('should set the implicit wait with an integer', function () {88 driver.setImplicitWait(42);89 driver.implicitWaitMs.should.eql(42);90 });91 describe('with managed driver', function () {92 let managedDriver1 = new BaseDriver();93 let managedDriver2 = new BaseDriver();94 before(function () {95 driver.addManagedDriver(managedDriver1);96 driver.addManagedDriver(managedDriver2);97 });...
implicit-wait-ext.js
Source:implicit-wait-ext.js
1function httpCommon(method, url, data, headers, callback) {2 var httpRequest = new XMLHttpRequest();3 //LOG.debug('Executing: ' + method + " " + url);4 httpRequest.open(method, url);5 httpRequest.onreadystatechange = function() {6 try {7 if (httpRequest.readyState === 4) {8 if (httpRequest.status === 200 || (httpRequest.status > 200 && httpRequest.status < 300)) {9 callback(httpRequest.responseText, true, httpRequest.status);10 } else if (httpRequest.status === 500 ) {11 callback(httpRequest.responseText, false, httpRequest.status);12 } else {13 //TODO eliminate alert and signal the failure14// alert('There was a problem with the request.\nUrl: ' + url + '\nHttp Status: ' + httpRequest.status + "\nResponse: " + httpRequest.responseText);15 LOG.debug('Error: There was a problem with the request.\nUrl: ' + url + '\nHttp Status: ' + httpRequest.status + "\nResponse: " + httpRequest.responseText);16 callback(null, false, httpRequest.status);17 }18 }19 } catch(e) {20 //TODO eliminate alert and signal the failure21 alert('Caught Exception in httpPost: ' + e);22 throw e;23 }24 };25 //httpRequest.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;26 for (var header in headers) {27 httpRequest.setRequestHeader(header, headers[header] + '');28 }29 if (data) {30 httpRequest.send(data);31 } else {32 httpRequest.send();33 }34}35function httpPost(url, data, headers, callback) {36 httpCommon('POST',url, data, headers, callback);37}38function httpGet(url, headers, callback) {39 httpCommon('GET',url, null, headers, callback);40}41/**42 * @Author : Florent BREHERET43 * @Function : Activate an implicite wait on action commands when trying to find elements.44 * @Param timeout : Timeout in millisecond, set 0 to disable the implicit wait45 * @Exemple 1 : setImplicitWaitLocator | 046 * @Exemple 1 : setImplicitWaitLocator | 100047 */48Selenium.prototype.doSetImplicitWaitLocator = function(timeout){49 if( !editor.implicitwait ) throw new SeleniumError("setImplicitWaitLocator works on Selenium IDE only ! ");50 if( timeout==0 ) {51 editor.implicitwait.locatorTimeout=0;52 editor.implicitwait.isImplicitWaitLocatorActivated=false;53 }else{54 editor.implicitwait.locatorTimeout=parseInt(timeout);55 editor.implicitwait.isImplicitWaitLocatorActivated=true;56 }57};58/**59 60 61 * @author : Florent BREHERET62 * @Function : Activate an implicite wait for condition before commands are executed.63 * @Param timeout : Timeout in millisecond, set 0 to disable the implicit wait64 * @Param condition_js : Javascript logical expression that need to be true to execute each command.65 *66 * @Exemple 0 : setImplicitWaitCondition | 0 | 67 * @Exemple 1 : setImplicitWaitCondition | 1000 | (typeof window.Sys=='undefined') ? true : window.Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()==false;68 * @Exemple 2 : setImplicitWaitCondition | 1000 | (typeof window.dojo=='undefined') ? true : window.dojo.io.XMLHTTPTransport.inFlight.length==0;69 * @Exemple 3 : setImplicitWaitCondition | 1000 | (typeof window.Ajax=='undefined') ? true : window.Ajax.activeRequestCount==0;70 * @Exemple 4 : setImplicitWaitCondition | 1000 | (typeof window.tapestry=='undefined') ? true : window.tapestry.isServingRequests()==false;71 * @Exemple 4 : setImplicitWaitCondition | 1000 | (typeof window.jQuery=='undefined') ? true : window.jQuery.active==0;72 */73Selenium.prototype.doSetImplicitWaitCondition = function( timeout, condition_js ) {74 if( !editor.implicitwait ) throw new SeleniumError("setImplicitWaitCondition works on Selenium IDE only ! ");75 if( timeout==0 ) {76 editor.implicitwait.conditionTimeout=0;77 editor.implicitwait.implicitAjaxWait_Condition=null;78 editor.implicitwait.implicitAjaxWait_Function=function(){return true;};79 editor.implicitwait.isImplicitWaitAjaxActivated=false;80 }else{81 editor.implicitwait.conditionTimeout=parseInt(timeout);82 editor.implicitwait.implicitAjaxWait_Condition=condition_js;83 selenium.getEval('editor.implicitwait.implicitAjaxWait_Function=function(){ return eval("' + condition_js + '");};');84 editor.implicitwait.isImplicitWaitAjaxActivated=true;85 }86}87Selenium.prototype.getUserAgent = function() {88 throw {89 haminiumStage: true,90 message: 'Go to haminium method'91 }...
validator-specs.js
Source:validator-specs.js
...28 });29 });30 describe('implicitWait', function () {31 it('should fail when given no ms', function () {32 (() => {validators.implicitWait();}).should.throw(/ms/i);33 });34 it('should fail when given a non-numeric ms', function () {35 (() => {validators.implicitWait('five');}).should.throw(/ms/i);36 });37 it('should fail when given a negative ms', function () {38 (() => {validators.implicitWait(-1);}).should.throw(/ms/i);39 });40 it('should succeed when given an ms of 0', function () {41 (() => {validators.implicitWait(0);}).should.not.throw();42 });43 it('should succeed when given an ms greater than 0', function () {44 (() => {validators.implicitWait(100);}).should.not.throw();45 });46 });47 describe('asyncScriptTimeout', function () {48 it('should fail when given no ms', function () {49 (() => {validators.asyncScriptTimeout();}).should.throw(/ms/i);50 });51 it('should fail when given a non-numeric ms', function () {52 (() => {validators.asyncScriptTimeout('five');}).should.throw(/ms/i);53 });54 it('should fail when given a negative ms', function () {55 (() => {validators.asyncScriptTimeout(-1);}).should.throw(/ms/i);56 });57 it('should succeed when given an ms of 0', function () {58 (() => {validators.asyncScriptTimeout(0);}).should.not.throw();...
expectation.methods.js
Source:expectation.methods.js
...4const HTMLHelper = require('./html.methods');5class ExpectationHelper {6 7 async verifyTextContainedInUrl(text) {8 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);9 await pageHelper.getCurrentUrl().then(function (currentUrl) {10 expect(currentUrl).toContain(text)11 });12 }13 async verifyElementContainsText(element, text) {14 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);15 element.getText().then(function (currentText) {16 expect(currentText).toContain(text)17 });18 }19 async verifyElementContainsValue(element, val) {20 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);21 element.getAttribute(HTMLHelper.attributes.value).then(function (currentText) {22 expect(currentText).toContain(val)23 });24 }25 async verifyElementDisplayed(element) {26 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);27 element.isDisplayed().then(function (isDisplayed) {28 expect(isDisplayed).toBeTrue();29 });30 }31 async verifyStringAreEquals(stringOne, stringTwo) {32 expect(stringOne).toEqual(stringTwo)33 }34 async verifyElementPresent(element) {35 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);36 element.isDisplayed().then(function (isDisplayed) {37 expect(isDisplayed).toBeTrue();38 });39 }40}...
expectation-helper.js
Source:expectation-helper.js
2const CommonConstant = require('../page-object/common-page/common-page.constant');3const HTMLHelper = require('../components/html-helper');4class ExpectationHelper {5 async verifyTextContainedInUrl(text) {6 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);7 driver.getCurrentUrl().then(function(currentUrl) {8 expect(currentUrl).toContain(text)9 });10 }11 async verifyElementContainsText(element, text) {12 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);13 element.getText().then(function(currentText) {14 expect(currentText).toContain(text)15 });16 }17 async verifyElementContainsValue(element, val) {18 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);19 element.getAttribute(HTMLHelper.attributes.value).then(function(currentText) {20 expect(currentText).toContain(val)21 });22 }23 async verifyElementDisplayed(element) {24 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);25 element.isDisplayed().then(function(isDisplayed) {26 expect(isDisplayed).toBeTrue();27 });28 }29 async verifyStringAreEquals(stringOne, stringTwo) {30 expect(stringOne).toEqual(stringTwo)31 }32 async verifyElementPresent(element) {33 await WaitHelper.implicitWait(CommonConstant.commonData.implicitWaitDefaultTimeout);34 element.isDisplayed().then(function(isDisplayed) {35 expect(isDisplayed).toBeTrue();36 });37 }38}...
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .waitForVisible('body', 10000)9 .setValue('input[name="q"]','webdriverio')10 .pause(2000)11 .keys('\uE007')12 .pause(2000)13 .getTitle().then(function(title) {14 console.log('Title is: ' + title);15 })16 .end();17exports.config = {18 capabilities: [{19 }],20 mochaOpts: {21 }22};
Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);7driver.findElement(By.name('q')).sendKeys('webdriver');8driver.findElement(By.name('btnG')).click();9driver.wait(until.titleIs('webdriver - Google Search'), 1000);10driver.quit();11var webdriver = require('selenium-webdriver'),12 until = webdriver.until;13var driver = new webdriver.Builder()14 .forBrowser('chrome')15 .build();16driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);17driver.findElement(By.name('q')).sendKeys('webdriver');18driver.findElement(By.name('btnG')).click();19driver.wait(until.titleIs('webdriver - Google Search'), 1000);20driver.quit();21var webdriver = require('selenium-webdriver'),22 until = webdriver.until;23var driver = new webdriver.Builder()24 .forBrowser('chrome')25 .build();26driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);27driver.findElement(By.name('q')).sendKeys('webdriver');28driver.findElement(By.name('btnG')).click();29driver.wait(until.titleIs('webdriver - Google Search'), 1000);30driver.quit();31var webdriver = require('selenium-webdriver'),32 until = webdriver.until;33var driver = new webdriver.Builder()34 .forBrowser('chrome')35 .build();36driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);37driver.findElement(By.name('q')).sendKeys('webdriver');38driver.findElement(By.name('btnG')).click();39driver.wait(until.titleIs('webdriver - Google Search'), 1000);40driver.quit();41var webdriver = require('selenium-webdriver'),
Using AI Code Generation
1const webdriverio = require('webdriverio');2const appium = require('appium');3const wdioAppiumService = require('wdio-appium-service');4const wdioAppiumService = require('wdio-appium-service');5const client = webdriverio.remote({6 capabilities: {7 }8});9client.init().then(function () {10 client.implicitWait(5000);11 client.findElement('accessibility id', 'buttonTestCD').click();12 client.findElement('accessibility id', 'editTextCD').setValue('Hello World!');13 client.findElement('accessibility id', 'buttonTestCD').click();14 client.findElement('accessibility id', 'editTextCD').getValue().then(function (text) {15 console.log(text);16 });17 client.end();18});19const webdriverio = require('webdriverio');20const appium = require('appium');21const wdioAppiumService = require('wdio-appium-service');22const wdioAppiumService = require('wdio-appium-service');23const client = webdriverio.remote({24 capabilities: {25 }26});27client.init().then(function () {
Using AI Code Generation
1describe('Appium Base Driver', function() {2 it('should use implicitWait', async function() {3 await driver.implicitWait(5000);4 await driver.elementByAccessibilityId('Alert Views').click();5 await driver.elementByAccessibilityId('Text Entry').click();6 await driver.elementByClassName('XCUIElementTypeTextField').sendKeys('Hello');7 await driver.elementByAccessibilityId('OK').click();8 });9});10exports.config = {11 capabilities: [{
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6var client = webdriverio.remote(options);7client.init().implicitWait(10000);8client.setValue('#lst-ib', 'webdriverio');9client.click('input[name="btnK"]');10client.getTitle().then(function(title) {11 console.log('Title is: ' + title);12});13client.end();
Using AI Code Generation
1driver.implicitWait(5000);2driver.waitUntil(function(){3 return driver.isDisplayed();4},5000);5driver.waitUntil(function(){6 return driver.isDisplayed();7},5000, 'Element is not displayed');8driver.waitUntil(function(){9 return driver.isDisplayed();10},5000, 'Element is not displayed', 500);11driver.waitUntil(function(){12 return driver.isDisplayed();13},5000, 500);14driver.waitUntil(function(){15 return driver.isDisplayed();16},5000, 500, 'Element is not displayed');17driver.waitUntil(function(){18 return driver.isDisplayed();19},5000, 'Element is not displayed', 500, 'Element is not displayed');20driver.waitUntil(function(){21 return driver.isDisplayed();22},5000, 500, 'Element is not displayed', 500, 'Element is not displayed');23driver.waitUntil(function(){24 return driver.isDisplayed();25},5000, 'Element is not displayed', 500, 'Element is not displayed', 500, 'Element is not displayed');26driver.waitUntil(function(){27 return driver.isDisplayed();28},5000, 500, 'Element is not displayed', 500, 'Element is not displayed', 500, 'Element is not displayed', 500, 'Element is not displayed');29driver.waitUntil(function(
Using AI Code Generation
1driver.implicitWait(5000);2driver.elementByAccessibilityId("SomeId", function(err, element) {3 element.click();4});5driver.implicitWait(5000);6driver.elementByAccessibilityId("SomeId", function(err, element) {7 element.click();8});9driver.implicitWait(5000);10driver.elementByAccessibilityId("SomeId", function(err, element) {11 element.click();12});13driver.implicitWait(5000);14driver.elementByAccessibilityId("SomeId", function(err, element) {15 element.click();16});17driver.implicitWait(5000);18driver.elementByAccessibilityId("SomeId", function(err, element) {19 element.click();20});21driver.implicitWait(5000);22driver.elementByAccessibilityId("SomeId", function(err, element) {23 element.click();24});25driver.implicitWait(5000);26driver.elementByAccessibilityId("SomeId", function(err, element) {27 element.click();28});29driver.implicitWait(5000);30driver.elementByAccessibilityId("SomeId", function(err, element) {31 element.click();32});33driver.implicitWait(5000);34driver.elementByAccessibilityId("SomeId", function(err, element) {35 element.click();36});37driver.implicitWait(5000);38driver.elementByAccessibilityId("SomeId", function(err, element) {39 element.click();40});41driver.implicitWait(5000);42driver.elementByAccessibilityId("SomeId", function(err, element) {43 element.click();44});45driver.implicitWait(5000);46driver.elementByAccessibilityId("SomeId", function(err, element) {47 element.click();48});49driver.implicitWait(500
Using AI Code Generation
1var webdriver = require('appium-base-driver').webdriver,2driver = new webdriver.Builder()3.withCapabilities({'app': 'com.android.contacts', 'platformName': 'Android'})4.build();5driver.manage().timeouts().implicitlyWait(3000);6driver.findElementByClassName('android.widget.TextView').click();7driver.findElementByClassName('android.widget.EditText').sendKeys('Hello World');8driver.quit();9driver.manage().timeouts().implicitlyWait(3000);10var webdriver = require('appium-base-driver').webdriver,11driver = new webdriver.Builder()12.withCapabilities({'app': 'com.android.contacts', 'platformName': 'Android'})13.build();14driver.manage().timeouts().implicitlyWait(3000);15driver.findElementByClassName('android.widget.TextView').click();16driver.findElementByClassName('android.widget.EditText').sendKeys('Hello World');17driver.quit();
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!!