Best JavaScript code snippet using webdriverio-monorepo
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 .setValue('*[name="q"]','webdriverio')9 .pause(1000)10 .keys('Enter')11 .pause(1000)12 .getTitle().then(function(title) {13 console.log('Title was: ' + title);14 })15 .end();
Using AI Code Generation
1describe('webdriver.io page', function() {2 it('should have the right title - the fancy generator way', function () {3 var title = browser.getTitle();4 console.log('Title was: ' + title);5 });6});7describe('webdriver.io page', function() {8 it('should have the right title - the fancy generator way', function () {9 var title = browser.getTitle();10 console.log('Title was: ' + title);11 });12});13describe('webdriver.io page', function() {14 it('should have the right title - the fancy generator way', function () {15 var title = browser.getTitle();16 console.log('Title was: ' + title);17 });18});19describe('webdriver.io page', function() {20 it('should have the right title - the fancy generator way', function () {21 var title = browser.getTitle();22 console.log('Title was: ' + title);23 });24});25describe('webdriver.io page', function() {26 it('should have the right title - the fancy generator way', function () {27 var title = browser.getTitle();28 console.log('Title was: ' + title);29 });30});31describe('webdriver.io page', function() {32 it('should have the right title - the fancy generator way', function () {33 var title = browser.getTitle();
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5}6var client = webdriverio.remote(options);7 .init()8 .waitForVisible('input[type="text"]', 5000)9 .setValue('input[type="text"]', 'WebdriverIO')10 .click('button[name="btnG"]')11 .pause(5000)12 .getTitle().then(function(title) {13 console.log('Title is: ' + title);14 })15 .end();
Using AI Code Generation
1describe('webdriver.io page', () => {2 it('should have the right title', () => {3 browser.implicitWait(3000);4 var title = browser.getTitle();5 console.log('Title was: ' + title);6 });7});8import org.openqa.selenium.By;9import org.openqa.selenium.WebDriver;10import org.openqa.selenium.WebElement;11import org.openqa.selenium.chrome.ChromeDriver;12import org.openqa.selenium.support.ui.WebDriverWait;13public class ImplicitWaitExample {14 public static void main(String[] args) {15 System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");16 WebDriver driver = new ChromeDriver();17 String expectedTitle = "Welcome: Mercury Tours";18 String actualTitle = "";19 driver.get(baseUrl);20 actualTitle = driver.getTitle();21 if (actualTitle.contentEquals(expectedTitle)){22 System.out.println("Test Passed!");23 } else {24 System.out.println("Test Failed");25 }26 WebElement userName = driver.findElement(By.name("userName"));27 userName.sendKeys("mercury");
Using AI Code Generation
1describe('webdriver.io page', () => {2 it('should have the right title', () => {3 browser.pause(3000);4 browser.implicitWait(3000);5 const title = browser.getTitle();6 expect(title).to.equal('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js');7 });8});9describe('webdriver.io page', () => {10 it('should have the right title', () => {11 browser.pause(3000);12 browser.setCookies({name: 'webdriver', value: 'io'});13 browser.pause(3000);14 const title = browser.getTitle();15 expect(title).to.equal('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js');16 });17});18describe('webdriver.io page', () => {19 it('should have the right title', () => {20 browser.pause(3000);21 browser.setCookies({name: 'webdriver', value: 'io'});22 browser.pause(3000);23 const cookie = browser.getCookie('webdriver');24 console.log(cookie);25 const title = browser.getTitle();26 expect(title).to.equal('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js');27 });28});29describe('webdriver.io page', () => {30 it('should have the right title', () => {31 browser.pause(3000);32 browser.setCookies({name: 'webdriver', value: 'io'});33 browser.pause(3000);34 browser.deleteCookie('webdriver');35 browser.pause(3000);36 const title = browser.getTitle();37 expect(title).to.equal('WebdriverIO · Next-gen
Using AI Code Generation
1describe('webdriver.io page', () => {2 it('should have the right title', () => {3 const title = browser.getTitle()4 assert.equal(title, 'WebdriverIO - WebDriver bindings for Node.js')5 })6})7describe('webdriver.io page', () => {8 it('should have the right title', () => {9 const title = browser.getTitle()10 assert.equal(title, 'WebdriverIO - WebDriver bindings for Node.js')11 })12})13describe('webdriver.io page', () => {14 it('should have the right title', () => {15 const title = browser.getTitle()16 assert.equal(title, 'WebdriverIO - WebDriver bindings for Node.js')17 })18})19describe('webdriver.io page', () => {20 it('should have the right title', () => {21 const title = browser.getTitle()22 assert.equal(title, 'WebdriverIO - WebDriver bindings for Node.js')23 })24})25describe('webdriver.io page', () => {26 it('should have the right title', () => {27 const title = browser.getTitle()28 assert.equal(title, 'WebdriverIO - WebDriver bindings for Node.js')29 })30})31describe('webdriver.io page', () => {32 it('should have the right title', () => {
Using AI Code Generation
1describe('Test to use implicitWait method of WebdriverIO', function() {2 it('Test to use implicitWait method of WebdriverIO', function () {3 browser.implicitWait(10000);4 browser.setValue('input[title="Search"]', 'WebdriverIO');5 browser.pause(5000);6 browser.click('input[value="Google Search"]');7 browser.pause(5000);8 });9});10exports.config = {11 capabilities: [{12 }],13 mochaOpts: {14 },15};
Using AI Code Generation
1describe('test webdriverio', () => {2 it('test webdriverio', () => {3 browser.implicitWait(10000);4 browser.setValue('#lst-ib', 'WebdriverIO');5 browser.click('#tsbb');6 browser.pause(5000);7 });8});9exports.config = {10 capabilities: [{11 }],12 mochaOpts: {13 }14};15describe('test webdriverio', () => {16 it('test webdriverio', () => {17 browser.setValue('#lst-ib', 'WebdriverIO');18 browser.click('#tsbb');19 browser.pause(5000);20 });21});22exports.config = {23 capabilities: [{24 }],25 mochaOpts: {26 }27};28I have tried with both the above test cases. In the first test case, I have used browser.implicitWait(10000); which is working fine. But in the second test case, I have not used browser.implicitWait(10000); and the test case is
Using AI Code Generation
1describe('Test WebdriverIO', function() {2 it('should test the webdriver.io page', function () {3 browser.pause(3000);4 var title = browser.getTitle();5 console.log("Title is: " + title);6 var searchInput = browser.element('#search_input_react');7 searchInput.setValue('WebdriverIO');8 browser.pause(3000);9 var searchButton = browser.element('.searchbox__button');10 searchButton.click();11 browser.pause(3000);12 browser.waitForExist('.search-result h4');13 var searchResult = browser.element('.search-result h4');14 var resultText = searchResult.getText();15 console.log("Search result is: " + resultText);16 });17});18exports.config = {19 {20 }
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!!