How to use driver.active method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

background.js

Source:background.js Github

copy

Full Screen

1/** @namespace */2ChromeDriver = {};3/**4 * Array of all information about currently loaded tabs (where a WebDriver5 * window is probably a tab)6 * Entries of form:7 * {Int tabId, String windowName, Port mainPort, FrameData[] frames}8 * FrameData ::= {[Int frameId], String frameName, Port framePort, FrameData[]}9 * frameId can be undefined, if it has not yet been looked up, but should be10 * added once it is known11 * @type {Array.<Object>} TODO(jmleyba): Type info12 */13ChromeDriver.tabs = [];14/**15 * Port to the currently active frame or tab (if focused on the main page).16 * @type {?Port}17 */18ChromeDriver.activePort = null;19/**20 * ID of the currently active tab.21 * @type {?string}22 */23ChromeDriver.activeTabId = null;24/**25 * Whether we should switch to the next tab which opens. Should be set if the26 * last active tab was closed.27 * @type {boolean}28 */29ChromeDriver.doFocusOnNextOpenedTab = true;30/**31 * Place to temporarily store the URL currently being loaded, so that we can32 * retry if needed, because opening a URL is an async callback.33 * @type {?string}34 */35ChromeDriver.urlBeingLoaded = null;36/**37 * URL we believe we're currently on.38 * @type {?string}39 */40ChromeDriver.currentUrl = null;41/**42 * Whether we are loading a new URL that difers from the current URL only in43 * fragment.44 * @type {boolean}45 */46ChromeDriver.isGettingUrlButOnlyChangingByFragment = false;47/**48 * Whether we are currently executing a {@code ChromeDriver#close()}, and49 * accordingly should send a success response when the tab closes.50 * @type {boolean}51 */52ChromeDriver.isClosingTab = false;53/**54 * Whether we have sent a response to the {currently, most recently loading55 * page.56 * @type {boolean}57 */58ChromeDriver.hasSentResponseToThisPageLoading = false;59/**60 * Whether we believe a page is open to which we have no content script.61 * @type {boolean}62 */63ChromeDriver.hasNoConnectionToPage = true;64/**65 * The last request we sent that has not been answered, so that if we change66 * page between sending a request and receiving a response, we can re-send it to67 * the newly loaded page.68 * @type {*} TODO(jmleyba)69 */70ChromeDriver.lastRequestToBeSentWhichHasntBeenAnsweredYet = null;71/**72 * Whether the plugin has the OS-specific window handle for the active tab. This73 * is called HWND rather than window handle to avoid confusion with the other74 * use of window handle to mean 'name of window'.75 * @type {boolean}76 */77ChromeDriver.hasHwnd = false;78/**79 * THe last XMLHttpRequest we made (used for communication with test language80 * bindings).81 * @type {?XMLHttpRequest}82 */83ChromeDriver.xmlHttpRequest = null;84/**85 * URL to ping for commands.86 * @type {string}87 */88ChromeDriver.xmlHttpRequestUrl = null;89/**90 * @type {number}91 */92ChromeDriver.requestSequenceNumber = 0;93/**94 * @type {number}95 */96ChromeDriver.lastReceivedSequenceNumber = -2;97/**98 * @type {number}99 */100ChromeDriver.getUrlRequestSequenceNumber = 0;101/**102 * Prefix prepended to the hopefully unique javascript window name, in hopes of103 * further removing conflict.104 * @type {string}105 */106ChromeDriver.windowHandlePrefix = '__webdriver_chromedriver_windowhandle';107/**108 * Whether we will not execute any commands because we are already executing109 * one.110 * @type {boolean}111 */112ChromeDriver.isBlockedWaitingForResponse = false;113/**114 * It's possible that the page has completed loading,115 * but the content script has not yet fired.116 * In this case, to not report that there is no page,117 * when we are just too fast, we wait up to this amount of time.118 * @type {number} unit: milliseconds119 */120ChromeDriver.timeoutUntilGiveUpOnContentScriptLoading = 5000;121/**122 * How long we are currently waiting for the content script to load123 * after loading the page124 * @type {number} unit: milliseconds125 */126ChromeDriver.currentlyWaitingUntilGiveUpOnContentScriptLoading;127/**128 * The amount of time, in milliseconds, to wait for an element to be located129 * when performing a search.130 * When searching for a single element, the driver will wait up to this amount131 * of time for the element to be located before returning an error.132 * When searching for multiple elements, the driver will wait up to this amount133 * of time for at least one element to be located before returning an empty134 * list.135 * @type {number}136 * @private137 */138ChromeDriver.implicitWait_ = 0;139/**140 * The amount of time, in milliseconds, to wait for an asynchronous script to141 * finish executing before returning an error to the client.142 * @type {number}143 * @private144 */145ChromeDriver.scriptTimeout_ = 0;146//Set ChromeDriver.currentlyWaitingUntilGiveUpOnContentScriptLoading;147resetCurrentlyWaitingOnContentScriptTime();148/**149 * How long we wait between poling whether we have a content script,150 * when loading a new page, up until151 * ChromeDriver.timeoutUntilGiveUpOnContentScriptLoading152 * @type {number} unit: milliseconds153 */154ChromeDriver.waitForContentScriptIncrement = 100;155chrome.extension.onRequest.addListener(function(request, sender, callback) {156 console.info('Received one-off request: ' + JSON.stringify(request));157 if (request == 'getExtensionId') {158 callback(sender.id);159 } else {160 console.error('...do not know how to handle request', JSON.stringify(request));161 }162});163chrome.extension.onConnect.addListener(function(port) {164 if (ChromeDriver.xmlHttpRequestUrl == null) {165 //This is the first content script, so is from the URL we need to connect to166 ChromeDriver.xmlHttpRequestUrl = port.tab.url;167 //Tell the ChromeCommandExecutor that we are here168 sendResponseByXHR("", false);169 return;170 } else if (port.tab.url.indexOf(ChromeDriver.xmlHttpRequestUrl) == 0) {171 //We have reloaded the xmlHttpRequest page. Ignore the connection.172 return;173 }174 console.log("Connected to " + port.name + " (" + port.portId_ + ")");175 ChromeDriver.hasNoConnectionToPage = false;176 var foundTab = false;177 for (var tab in ChromeDriver.tabs) {178 if (ChromeDriver.tabs[tab].tabId == port.tab.id ) {179 //We must be a new page or [i]frame in the page, because when a page closes, it is180 // removed from ChromeDriver.tabs181 //TODO(danielwh): Work out WHICH page it's a sub-frame of (I don't look182 // forward to this)183 ChromeDriver.tabs[tab].frames.push({184 frameName: port.name,185 framePort: port,186 frames: []187 });188 //Loaded a frame. Pushed it to the array. We don't know which page it's189 // a sub-frame of, in the case of nested frames, if they have the same190 // names. It would be nice to think people didn't use frames, let alone191 // several layers of nesting of frames with the same name, but if it turns192 // out to be a problem... Well, we'll see.193 foundTab = true;194 console.log("Found tab");195 break;196 }197 }198 if (!foundTab) {199 //New tab!200 ChromeDriver.tabs.push({201 tabId: port.tab.id,202 windowName: ChromeDriver.windowHandlePrefix + "_" + port.tab.id,203 frames: [{frameName: port.name, framePort: port, frames: []}]204 });205 }206 207 if (ChromeDriver.urlBeingLoaded != null) {208 //This was the result of a getUrl. Need to issue a response209 sendEmptyResponseWhenTabIsLoaded(port.tab); 210 }211 port.onMessage.addListener(function(message) {parsePortMessage(message, port)});212 port.onDisconnect.addListener(function disconnectPort(port) {213 console.log("Disconnected from " + port.name + " portID_("+port.portId_+")");214 var remainingTabs = [];215 for (var tab in ChromeDriver.tabs) {216 if (ChromeDriver.tabs[tab].tabId == port.tab.id) {217 if (ChromeDriver.tabs[tab].mainPort == port) {218 //This main tab is being closed.219 //Don't include it in the new version of ChromeDriver.tabs.220 //Any subframes will also disconnect,221 //but their tabId won't be present in the array,222 //so they will be ignored.223 continue;224 } else {225 //This is a subFrame being ditched226 var remainingFrames = [];227 for (var frame in ChromeDriver.tabs[tab].frames) {228 if (ChromeDriver.tabs[tab].frames[frame].framePort == port) {229 continue;230 }231 remainingFrames.push(ChromeDriver.tabs[tab].frames[frame]);232 }233 ChromeDriver.tabs[tab].frames = remainingFrames;234 }235 }236 remainingTabs.push(ChromeDriver.tabs[tab]);237 }238 ChromeDriver.tabs = remainingTabs;239 if (ChromeDriver.tabs.length == 0 || ChromeDriver.activePort == null ||240 ChromeDriver.activePort.tab.id == port.tab.id) {241 //If it is the active tab, perhaps we have followed a link,242 //so we should focus on it.243 //We have nothing better to focus on, anyway.244 //resetActiveTabDetails();245 console.log("292");246 ChromeDriver.doFocusOnNextOpenedTab = true;247 resetCurrentlyWaitingOnContentScriptTime();248 }249 if (ChromeDriver.isClosingTab) {250 //We are actively closing the tab, and expect a response to this251 sendResponseToParsedRequest({status: 0}, false)252 ChromeDriver.isClosingTab = false;253 if (ChromeDriver.tabs.length == 0) {254 chrome.windows.getAll({}, function(windows) {255 for (var window in windows) {256 chrome.windows.remove(windows[window].id);257 }258 });259 }260 }261 });262});263/**264 * Sends the passed argument as the result of a command265 * @param result object encapsulating result to send266 * @param wait whether we expect this command to possibly make changes267 * we need to wait for (e.g. adding elements, opening windows) - if so,268 * we wait until we think these effects are done269 */270function sendResponseByXHR(result, wait) {271 //console.log("Sending result by XHR: " + JSON.stringify(result));272 if (ChromeDriver.xmlHttpRequest != null) {273 ChromeDriver.xmlHttpRequest.abort();274 }275 ChromeDriver.xmlHttpRequest = new XMLHttpRequest();276 ChromeDriver.xmlHttpRequest.onreadystatechange =277 handleXmlHttpRequestReadyStateChange;278 ChromeDriver.xmlHttpRequest.open(279 "POST", ChromeDriver.xmlHttpRequestUrl, true);280 ChromeDriver.xmlHttpRequest.setRequestHeader(281 "Content-type", "application/json");282 //Default to waiting for page changes, just in case283 //TODO(danielwh): Iterate over tabs checking their status284 if (wait === undefined || wait == null || wait) {285 setTimeout(sendResult, 600, [result]);286 } else {287 sendResult(result);288 }289}290/**291 * Actually sends the result by XHR292 * Should only EVER be called by sendResponseByXHR,293 * as it ignores things like setting up XHR and blocking,294 * and just forces the sending over an assumed open XHR295 * @param result String to send296 */297function sendResult(result) {298 //TODO(danielwh): Iterate over tabs checking their status299 ChromeDriver.xmlHttpRequest.send(result + "\nEOResponse\n");300 // console.log("Sent result by XHR: " + JSON.stringify(result));301}302/**303 * Sends the response to a request, which has been parsed by parseRequest304 * Should be used only from within parseRequest (or methods called from it),305 * because it adheres to the blocking semantics of parseRequest306 */307function sendResponseToParsedRequest(toSend, wait) {308 if (!ChromeDriver.isBlockedWaitingForResponse) {309 console.log("Tried to send a response (" + toSend +310 ") when not waiting for one. Dropping response.");311 return;312 }313 ChromeDriver.isBlockedWaitingForResponse = false;314 ChromeDriver.lastRequestToBeSentWhichHasntBeenAnsweredYet = null;315 // console.log("SENDING RESPOND TO PARSED REQUEST");316 toSend['sessionId'] = 'static_session_id'; 317 sendResponseByXHR(JSON.stringify(toSend), wait);318 setExtensionBusyIndicator(false);319}320/**321 * When we receive a request, dispatches parseRequest to execute it322 */323function handleXmlHttpRequestReadyStateChange() {324 if (this.readyState == 4) {325 if (this.status != 200) {326 console.log("Request state was 4 but status: " + this.status +327 ". responseText: " + this.responseText);328 } else {329 //console.log("GOT XHR RESPONSE: " + this.responseText);330 var request = JSON.parse(this.responseText);331 if (request.request == "quit") {332 //We're only allowed to send a response if we're blocked waiting for one, so pretend333 console.log("SENDING QUIT XHR");334 sendResponseByXHR(JSON.stringify({status: 0}), false);335 } else {336 // console.log("Got request to execute from XHR: " + this.responseText);337 parseRequest(request);338 }339 }340 }341}342/**343 * Parses a request received from the ChromeCommandExecutor and either sends the344 * response, or sends a message to the content script with a command to execute345 * @param request object encapsulating the request (e.g.346 * {request: url, url: "http://www.google.co.uk"})347 */348function parseRequest(request) {349 if (ChromeDriver.isBlockedWaitingForResponse) {350 console.log("Already sent a request which hasn't been replied to yet. " +351 "Not parsing any more.");352 return;353 }354 ChromeDriver.isBlockedWaitingForResponse = true;355 setExtensionBusyIndicator(true);356 357 switch (request.request) {358 case "newSession":359 sendResponseToParsedRequest({360 status: 0,361 value: {362 'browserName': 'chrome',363 'version': navigator.appVersion.replace(/.*Chrome\/(\d(\.\d+)*\b).*/, "$1"),364 'platform': navigator.platform,365 'javascriptEnabled': true,366 }367 });368 break;369 case "get":370 getUrl(request.url);371 break;372 case "close":373 //Doesn't re-focus the ChromeDriver.activePort on any tab.374 chrome.tabs.remove(ChromeDriver.activeTabId);375 ChromeDriver.isClosingTab = true;376 break;377 case "getCurrentWindowHandle":378 if (ChromeDriver.activePort == null) {379 // console.log("No active port right now.");380 // Fine. Find the active tab.381 // TODO(simon): This is lame and error prone382 var len = ChromeDriver.tabs.length;383 for (var i = 0; i < len; i++) {384 if (ChromeDriver.tabs[i].selected) {385 sendResponseToParsedRequest({status: 0, value: ChromeDriver.tabs[i].id}, false);386 }387 }388 // Hohoho. The first argument to tabs.getSelected is optional, but must be set.389 chrome.windows.getCurrent(function(win) {390 chrome.tabs.getSelected(win.id, function(tab) {391 var len = ChromeDriver.tabs.length;392 for (var i = 0; i < len; i++) {393 if (ChromeDriver.tabs[i].tabId == tab.id) {394 sendResponseToParsedRequest({status: 0, value: ChromeDriver.tabs[i].tabId}, false);395 return;396 }397 }398 });399 });400 } else {401 // Wow. I can't see this being error prone in the slightest402 var handle = ChromeDriver.windowHandlePrefix + "_" + ChromeDriver.activePort.sender.tab.id;403 sendResponseToParsedRequest({status: 0, value: handle}, false);404 };405 break;406 case "getWindowHandles":407 sendResponseToParsedRequest(getWindowHandles(), false);408 break;409 case "switchToFrame":410 switchToFrame(request.id);411 break;412 case "switchToWindow":413 ChromeDriver.hasHwnd = false;414 if (request.name !== undefined) {415 setActivePortByWindowName(request.name);416 } else {417 sendResponseToParsedRequest({418 status: 23,419 value: {420 message: 'Window to switch to was not given'421 }422 }, false);423 }424 break;425 case "screenshot":426 getScreenshot();427 break;428 case "implicitlyWait":429 ChromeDriver.implicitWait_ = request.ms || 0;430 sendResponseToParsedRequest({status: 0});431 break;432 case "setScriptTimeout":433 ChromeDriver.scriptTimeout_ = request.ms || 0;434 sendResponseToParsedRequest({status: 0});435 break;436 case "deleteCookie":437 chrome.cookies.remove({url: ChromeDriver.currentUrl, name: request.name});438 sendResponseToParsedRequest({status: 0});439 break;440 case "deleteAllCookies":441 chrome.cookies.getAll({url: ChromeDriver.currentUrl}, deleteAllCookies);442 break;443 case "getCookie":444 chrome.cookies.get({url: ChromeDriver.currentUrl, name: request.name}, getCookieCallback);445 break;446 case "getCookies":447 chrome.cookies.getAll({url: ChromeDriver.currentUrl}, getAllCookiesCallback);448 break;449 //TODO: Use this code-path when http://crbug.com/56211 is fixed450 /*case "addCookie":451 if (hasNoPage()) {452 console.log("Not got a page, but asked to set cookie");453 sendResponseToParsedRequest({status: 25, value: 'Cannot set a cookie when not on a page'});454 break;455 }456 addCookie(request.cookie);457 break;*/458 case "executeScript":459 if (hasNoPage()) {460 console.log("Not got a page, but asked to execute script, so sending error 17");461 sendResponseToParsedRequest({status: 17, value: {message: 'Was not on a page, so could not execute javascript'}});462 break;463 }464 if(request.script.indexOf("window.resizeTo(") === 0){465 var opt = {};466 var theMatch = request.script.match(/window.resizeTo\((\d+),(\d+)\);/);467 opt.width = parseInt(theMatch[1]);468 opt.height = parseInt(theMatch[2]);469 chrome.windows.getCurrent(function (win){470 opt.left = win.left;471 opt.top = win.top;472 chrome.windows.update( win.id, opt, function(dontCare){473 sendResponseToParsedRequest({status: 0, value: null});474 });475 });476 }477 // Falling through, as if we do have a page, we want to treat this like a478 // normal request479 case "clickElement":480 case "hoverOverElement":481 // Falling through, as native events are handled the same482 case "sendKeysToElement":483 if (typeof(request.keys) == "object" && request.keys.length !== undefined) {484 request.keys = request.keys.join("");485 }486 sendMessageOnActivePortAndAlsoKeepTrackOfIt(487 wrapInjectEmbedIfNecessary(request));488 break;489 case "getCurrentUrl":490 case "getTitle":491 if (hasNoPage()) {492 console.log("Not got a page, but asked for string, so sending empty string");493 sendResponseToParsedRequest({status: 0, value: ''});494 break;495 }496 // Falling through, as if we do have a page, we want to treat this like a497 // normal request498 case "findElement":499 case "findChildElement":500 if (hasNoPage()) {501 console.log("Not got a page, but asked for element, so throwing NoSuchElementException");502 sendResponseToParsedRequest({status: 7, value: {message: 'Was not on a page, so could not find elements'}});503 break;504 }505 // Falling through, as if we do have a page, we want to treat this like a506 // normal request507 case "findElements":508 case "findChildElements":509 if (hasNoPage()) {510 console.log("Not got a page, but asked for elements, so returning no elements");511 sendResponseToParsedRequest({status: 0, value: []});512 break;513 }514 // Falling through, as if we do have a page, we want to treat this like a515 // normal request516 default:517 var sequenceNumber = ChromeDriver.requestSequenceNumber;518 ChromeDriver.requestSequenceNumber++;519 sendMessageOnActivePortAndAlsoKeepTrackOfIt({520 request: request,521 sequenceNumber: sequenceNumber,522 implicitWait: ChromeDriver.implicitWait_,523 asyncTimeout: ChromeDriver.scriptTimeout_524 });525 break;526 }527}528function getScreenshot() {529 chrome.tabs.captureVisibleTab(null, getScreenshotResult);530}531function getScreenshotResult(snapshotDataUrl) {532 var index = snapshotDataUrl.indexOf('base64,');533 if (index == -1) {534 sendResponseToParsedRequest({status: 99}, false);535 return;536 }537 var base64 = snapshotDataUrl.substring(index + 'base64,'.length);538 sendResponseToParsedRequest({status: 0, value: base64}, false);539}540function sendMessageOnActivePortAndAlsoKeepTrackOfIt(message) {541 ChromeDriver.lastRequestToBeSentWhichHasntBeenAnsweredYet = message.request;542 try {543 ChromeDriver.activePort.postMessage(message);544 } catch (e) {545 console.log("Tried to send request without an active port. " +546 "Request will retry when connected, but will hang until then.");547 }548}549/**550 * Parse messages coming in on the port (responses from the content script).551 * @param message JSON message of format:552 * {response: "some command",553 * value: {statusCode: STATUS_CODE554 * [, optional params]}}555 */556function parsePortMessage(message, port) {557 /*console.log(558 "Received response from content script: " + JSON.stringify(message));*/559 if (!message || !message.response || !message.response.value ||560 message.response.value.statusCode === undefined ||561 message.response.value.statusCode === null ||562 message.sequenceNumber === undefined || message.sequenceNumber < ChromeDriver.lastReceivedSequenceNumber) {563 // Should only ever happen if we sent a bad request,564 // or the content script is broken565 console.log("Got invalid response from the content script.");566 return;567 }568 var toSend = {status: 12};569 ChromeDriver.lastRequestToBeSentWhichHasntBeenAnsweredYet = null;570 switch (message.response.value.statusCode) {571 // Error codes are loosely based on native exception codes, see572 // common/src/cpp/webdriver-interactions/errorcodes.h573 case 0:574 case 7: //org.openqa.selenium.NoSuchElementException575 case 8: //org.openqa.selenium.NoSuchFrameException576 case 9: //java.lang.UnsupportedOperationException [Unknown command]577 case 10: //org.openqa.selenium.StaleElementReferenceException578 case 11: //org.openqa.selenium.ElementNotVisibleException579 case 12: //java.lang.UnsupportedOperationException [Invalid element state ]580 case 13: //org.openqa.selenium.WebDriverException [Unhandled error]581 case 17: //org.openqa.selenium.WebDriverException [Bad javascript]582 case 19: //org.openqa.selenium.XPathLookupException583 case 23: //org.openqa.selenium.NoSuchWindowException584 case 24: //org.openqa.selenium.InvalidCookieDomainException585 case 25: //org.openqa.selenium.UnableToSetCookieException586 case 28: //org.openqa.selenium.TimeoutException587 case 99: //org.openqa.selenium.WebDriverException [Native event]588 toSend = {status: message.response.value.statusCode, value: null};589 if (message.response.value !== undefined && message.response.value !== null &&590 message.response.value.value !== undefined) {591 toSend.value = message.response.value.value;592 }593 sendResponseToParsedRequest(toSend, message.response.wait);594 break;595 case "no-op":596 //Some special operation which isn't sending HTTP597 switch (message.response.response) {598 case "clickElement":599 try {600 if (document.embeds[0].clickAt(message.response.value.x, message.response.value.y)) {601 sendResponseToParsedRequest({status: 0}, true);602 } else {603 sendResponseToParsedRequest({status: 99}, true);604 }605 } catch(e) {606 console.log("Error natively clicking. Trying non-native.");607 ChromeDriver.isBlockedWaitingForResponse = false;608 parseRequest({609 request: 'nonNativeClickElement',610 id: message.response.value.id611 });612 }613 break;614 case "hoverElement":615 try {616 var points = message.response.value;617 if (document.embeds[0].mouseMoveTo(15, points.oldX, points.oldY, points.newX, points.newY)) {618 sendResponseToParsedRequest({status: 0}, true);619 } else {620 sendResponseToParsedRequest({status: 99}, true);621 }622 } catch(e) {623 sendResponseToParsedRequest({status: 99}, true);624 }625 break;626 case "sendKeysToElement":627 try {628 if (document.embeds[0].sendKeys(message.response.value.keys)) {629 sendResponseToParsedRequest({status: 0}, true);630 } else {631 sendResponseToParsedRequest({status: 99}, true);632 }633 } catch(e) {634 console.log("Error natively sending keys. Trying non-native.");635 ChromeDriver.isBlockedWaitingForResponse = false;636 parseRequest({637 request: 'sendElementNonNativeKeys',638 id: message.response.value.id,639 keys: message.response.value.keys640 });641 }642 break;643 case "sniffForMetaRedirects":644 if (!message.response.value.value &&645 !ChromeDriver.hasSentResponseToThisPageLoading) {646 ChromeDriver.urlBeingLoaded = null;647 ChromeDriver.hasSentResponseToThisPageLoading = true;648 switchToFrame(null);649 }650 break;651 case "newTabInformation":652 var response = message.response.value;653 console.log("port.tab.id: " + port.tab.id + ", defaultContent: " + response.isDefaultContent);654 for (var tab in ChromeDriver.tabs) {655 if (ChromeDriver.tabs[tab].tabId == port.tab.id) {656 if (response.isDefaultContent) {657 ChromeDriver.tabs[tab].mainPort = port;658 }659 }660 }661 if (ChromeDriver.doFocusOnNextOpenedTab && response.isDefaultContent) {662 ChromeDriver.activePort = port;663 console.log(">>>[705] Setting ChromeDriver.activePort to " + port+ " portID = "+port.portId_);664 setActiveTabDetails(port.tab);665 //Re-parse the last request we sent if we didn't get a response,666 //because we ain't seeing a response any time soon667 668 if (ChromeDriver.lastRequestToBeSentWhichHasntBeenAnsweredYet != null) {669 if (ChromeDriver.urlBeingLoaded != null) {670 ChromeDriver.lastRequestToBeSentWhichHasntBeenAnsweredYet = null;671 } else {672 ChromeDriver.isBlockedWaitingForResponse = false;673 console.log("Re-trying request which was sent but not answered");674 parseRequest(ChromeDriver.lastRequestToBeSentWhichHasntBeenAnsweredYet);675 }676 }677 }678 break;679 case "switchToFrame":680 console.info([681 'Got a no-op response to a switchToFrame command. This means that',682 ' the port that sent the response is the new active port.',683 '-- Old Port Info ---------------------------------------',684 ' name: ' + ChromeDriver.activePort,685 ' tab ID: ' + ChromeDriver.activePort.tab.id,686 '-- New Port Info ---------------------------------------',687 ' name: ' + port,688 ' tab ID: ' + port.tab.id689 ].join('\n'));690 ChromeDriver.activePort = port;691 console.log(">>>[733] Setting ChromeDriver.activePort to " + ChromeDriver.activePort);692 sendResponseToParsedRequest({status: 0}, false);693 break;694 default:695 console.log(">>[737] Replying to " + message.response.response +" as default");696 sendResponseToParsedRequest({status: 0}, false);697 }698 break;699 }700}701/**702 * If the plugin doesn't currently have an HWND for this page,703 * we need to get one by injecting an embed704 */705function wrapInjectEmbedIfNecessary(requestObject) {706 if (ChromeDriver.hasHwnd) {707 var sequenceNumber = ChromeDriver.requestSequenceNumber;708 ChromeDriver.requestSequenceNumber++;709 return {710 sequenceNumber: sequenceNumber,711 request: requestObject712 };713 } else {714 var wrappedObject = {715 sequenceNumber: ChromeDriver.requestSequenceNumber,716 request: {717 request: "injectEmbed",718 followup: {719 sequenceNumber: ChromeDriver.requestSequenceNumber + 1,720 request: requestObject721 }722 }723 };724 ChromeDriver.requestSequenceNumber += 2;725 return wrappedObject;726 }727}728/**729 * Gets all current window handles730 * @return an array containing all of the current window handles731 */732function getWindowHandles() {733 var windowHandles = [];734 for (var tab in ChromeDriver.tabs) {735 windowHandles.push(ChromeDriver.tabs[tab].windowName);736 }737 return {status: 0, value: windowHandles}738}739var aboutToChangeTabsInfo;740function resetActiveTabDetails() {741 ChromeDriver.activePort = null;742 ChromeDriver.hasHwnd = false;743 ChromeDriver.activeTabId = null;744 ChromeDriver.doFocusOnNextOpenedTab = true;745 ChromeDriver.hasSentResponseToThisPageLoading = false;746 ChromeDriver.currentUrl = null;747 resetCurrentlyWaitingOnContentScriptTime();748}749function setActiveTabDetails(tab) {750 ChromeDriver.activeTabId = tab.id;751 ChromeDriver.activeWindowId = tab.windowId;752 ChromeDriver.doFocusOnNextOpenedTab = false;753 ChromeDriver.currentUrl = tab.url;754 resetCurrentlyWaitingOnContentScriptTime();755}756function switchToFrame(id) {757 ChromeDriver.hasHwnd = false;758 if(id == "WaRRResetFrame") {759 console.log("SILVIU RESSETING THE CURRENT FRAME");760 ChromeDriver.activePort.postMessage({761 request: {762 request: 'switchToFrame',763 // id may not always be a reference to an element, so we cannot764 // use the "id" key.765 locator: "WaRRReset"766 },767 sequenceNumber: ChromeDriver.requestSequenceNumber++768 });769 }770 if (id === undefined || id === null || id == "WaRRResetFrame") {771 console.info('Switching to default content');772 var firstTab = null;773 for (var tab in ChromeDriver.tabs) {774 if (ChromeDriver.tabs[tab].tabId == ChromeDriver.activeTabId) {775 if(!firstTab){776 firstTab = ChromeDriver.tabs[tab].mainPort;777 }778 if(ChromeDriver.tabs[tab].frames.length > 1) {779 ChromeDriver.activePort = ChromeDriver.tabs[tab].mainPort;780 console.log("Selected: " + firstTab);781 ChromeDriver.isBlockedWaitingForResponse = true;782 sendResponseToParsedRequest({status: 0}, false);783 return;784 }785 }786 }787 if(firstTab){788 ChromeDriver.activePort = firstTab;789 console.log(">>>[820] Setting ChromeDriver.activePort to " + ChromeDriver.activePort+ " portID = "+ChromeDriver.activePort.portId_);790 sendResponseToParsedRequest({status: 0}, false);791 console.log("Selected: " + firstTab);792 }793 } else if (typeof id == 'number' ||794 typeof id == 'string' ||795 typeof id == 'object' && 'ELEMENT' in id) {796 console.info('Instructing current page to locate and activate frame: ',797 JSON.stringify(id));798 ChromeDriver.isBlockedWaitingForResponse = true;799 ChromeDriver.activePort.postMessage({800 request: {801 request: 'switchToFrame',802 // id may not always be a reference to an element, so we cannot803 // use the "id" key.804 locator: id805 },806 sequenceNumber: ChromeDriver.requestSequenceNumber++807 });808 } else {809 sendResponseToParsedRequest({810 status: 9,811 value: {812 message: 'Invalid frame selector: ' + JSON.stringify(id)813 }814 });815 }816}817/**818 * Closes the current tab if it exists, and opens a new one, in which it819 * gets the URL passed820 * @param url the URL to load821 */822function getUrl(url) {823 ChromeDriver.urlBeingLoaded = url;824 var tempActiveTagId = ChromeDriver.activeTabId;825 if (url.indexOf("#") > -1 && ChromeDriver.currentUrl != null &&826 ChromeDriver.currentUrl.split("#")[0] == url.split("#")[0]) {827 ChromeDriver.isGettingUrlButOnlyChangingByFragment = true;828 } else {829 resetActiveTabDetails();830 }831 ChromeDriver.currentUrl = url;832 if (tempActiveTagId == null) {833 chrome.tabs.create({url: url, selected: true}, getUrlCallback);834 } else {835 ChromeDriver.activeTabId = tempActiveTagId;836 if (ChromeDriver.isGettingUrlButOnlyChangingByFragment) {837 chrome.tabs.update(ChromeDriver.activeTabId, {url: url, selected: true},838 getUrlCallback);839 } else {840 // we need to create the new tab before deleting the old one841 // in order to avoid hanging on OS X842 var oldId = ChromeDriver.activeTabId;843 resetActiveTabDetails();844 chrome.tabs.create({url: url, selected: true}, getUrlCallback);845 chrome.tabs.remove(oldId);846 }847 }848}849function getUrlCallback(tab) {850 if (chrome.extension.lastError) {851 // An error probably arose because Chrome didn't have a window yet852 // (see crbug.com 19846)853 // If we retry, we *should* be fine. Unless something really bad is854 // happening, in which case we will probably hang indefinitely trying to855 // reload the same URL856 getUrl(ChromeDriver.urlBeingLoaded);857 return;858 }859 if (tab == null) {860 //chrome.tabs.update's callback doesn't pass a Tab argument,861 //so we need to populate it ourselves862 chrome.tabs.get(ChromeDriver.activeTabId, getUrlCallback);863 return;864 }865 if (tab.status != "complete") {866 // Use the helper calback so that we actually get updated version of the tab867 // we're getting868 setTimeout("getUrlCallbackById(" + tab.id + ")", 10);869 } else {870 ChromeDriver.getUrlRequestSequenceNumber++;871 if (ChromeDriver.activePort == null) {872 if (ChromeDriver.currentlyWaitingUntilGiveUpOnContentScriptLoading <= 0) {873 ChromeDriver.hasNoConnectionToPage = true;874 sendEmptyResponseWhenTabIsLoaded(tab);875 } else {876 ChromeDriver.currentlyWaitingUntilGiveUpOnContentScriptLoading -=877 ChromeDriver.waitForContentScriptIncrement;878 setTimeout("getUrlCallbackById(" + tab.id + ")", ChromeDriver.waitForContentScriptIncrement);879 return;880 }881 }882 setActiveTabDetails(tab);883 }884 if (ChromeDriver.isGettingUrlButOnlyChangingByFragment) {885 ChromeDriver.urlBeingLoaded = null;886 resetCurrentlyWaitingOnContentScriptTime();887 sendResponseToParsedRequest({status: 0}, false);888 ChromeDriver.isGettingUrlButOnlyChangingByFragment = false;889 }890}891function getUrlCallbackById(tabId) {892 chrome.tabs.get(tabId, getUrlCallback);893}894function sendEmptyResponseWhenTabIsLoaded(tab) {895 if (tab.status == "complete") {896 if (ChromeDriver.activePort) {897 ChromeDriver.isBlockedWaitingForResponse = false;898 parseRequest({request: 'sniffForMetaRedirects'});899 } else {900 if (!ChromeDriver.hasSentResponseToThisPageLoading) {901 ChromeDriver.urlBeingLoaded = null;902 sendResponseToParsedRequest({status: 0}, false);903 }904 }905 } else {906 chrome.tabs.get(tab.id, sendEmptyResponseWhenTabIsLoaded);907 }908}909 910function setExtensionBusyIndicator(busy) {911 if (busy) {912 chrome.browserAction.setIcon({path: "icons/busy.png"})913 } else {914 chrome.browserAction.setIcon({path: "icons/free.png"})915 }916}917function setActivePortByWindowName(handle) {918 for (var tab in ChromeDriver.tabs) {919 if (ChromeDriver.tabs[tab].windowName == handle || 920 (ChromeDriver.tabs[tab].mainPort !== undefined && ChromeDriver.tabs[tab].mainPort.name == handle) ||921 ChromeDriver.tabs[tab].tabId.toString() == handle) {922 ChromeDriver.activePort = ChromeDriver.tabs[tab].mainPort;923 console.log(">>>[957] Set active port to "+ChromeDriver.tabs[tab].mainPort);924 chrome.tabs.get(ChromeDriver.tabs[tab].tabId, setActiveTabDetails);925 chrome.tabs.update(ChromeDriver.tabs[tab].tabId, {selected: true});926 sendResponseToParsedRequest({status: 0}, false);927 return;928 }929 }930 sendResponseToParsedRequest({status: 23, value: {message: 'Could not find window to switch to by handle: ' + handle}}, false);931}932function addCookie(passedCookie) {933 ChromeDriver.isWaitingForCookieToBeSet = true;934 var cookie = {};935 cookie.url = ChromeDriver.currentUrl;936 cookie.name = passedCookie.name;937 if (passedCookie.value !== undefined) {938 cookie.value = passedCookie.value;939 }940 if (passedCookie.domain !== undefined) {941 cookie.domain = passedCookie.domain;942 }943 if (passedCookie.path !== undefined) {944 cookie.path = passedCookie.path;945 }946 if (passedCookie.isSecure !== undefined) {947 cookie.secure = passedCookie.isSecure;948 }949 //TODO: Set expires950 /*if (passedCookie.expirationDate !== undefined) {951 cookie.path = passedCookie.path;952 }*/953 954 console.log(passedCookie);955 console.log(cookie);956 chrome.cookies.set(cookie);957}958function formatCookie(cookie) {959 return {name: cookie.name, value: cookie.value, path: cookie.path, domain: cookie.domain, expiry: cookie.expirationDate, secure: cookie.secure};960}961function getAllCookiesCallback(cookies) {962 var cookiesToReturn = [];963 for (var c in cookies) {964 cookiesToReturn.push(formatCookie(cookies[c]));965 }966 sendResponseToParsedRequest({status: 0, value: cookiesToReturn});967}968function getCookieCallback(cookie) {969 sendResponseToParsedRequest({status: 0, value: formatCookie(cookie)});970}971function deleteAllCookies(cookies) {972 for (var cookie in cookies) {973 chrome.cookies.remove({url: ChromeDriver.currentUrl, name: cookies[cookie].name});974 }975 sendResponseToParsedRequest({status: 0});976}977/**978 * @return {boolean} Whether there is currently no active page.979 */980function hasNoPage() {981 //console.log(ChromeDriver.hasNoConnectionToPage + " "+ChromeDriver.activePort+" "+ChromeDriver.activeTabId);982 return ChromeDriver.hasNoConnectionToPage ||983 ChromeDriver.activePort == null ||984 ChromeDriver.activeTabId == null;985}986function resetCurrentlyWaitingOnContentScriptTime() {987 console.log('resetting current content script wait time');988 ChromeDriver.currentlyWaitingUntilGiveUpOnContentScriptLoading =989 ChromeDriver.timeoutUntilGiveUpOnContentScriptLoading;...

Full Screen

Full Screen

run-test.js

Source:run-test.js Github

copy

Full Screen

1// @flow2import type {Driver} from 'cabbie-async';3import {getSessions, getStatus, MouseButtons, SelectorTypes} from 'cabbie-async';4import chalk from 'chalk';5import assert from 'assert';6async function test(name: string, fn: () => Promise<void>) {7 console.log(chalk.blue(name));8 await fn();9}10async function run(driver: Driver, location: string) {11 async function checkText(elementSelector: string, expectedText: string) {12 const element = await driver.activeWindow.getElement(elementSelector);13 const actualText = await element.getText();14 assert.equal(actualText, expectedText);15 return element;16 }17 await test('test timeouts', async () => {18 await driver.timeOut.setTimeOuts({implicit: '1s', async: '10s'});19 });20 await test('get the active window handle', async () => {21 const activeWindowHandle = await driver.activeWindow.getWindowHandle();22 assert.notEqual(activeWindowHandle.id, 'current');23 assert.equal(typeof activeWindowHandle.id, 'string');24 });25 await test('navigate to a domain', async () => {26 await driver.activeWindow.navigateTo(location);27 });28 await test('get the url of the active window', async () => {29 assert.equal(await driver.activeWindow.getUrl(), location);30 });31 await test('select a single element', async () => {32 const alertButton = await driver.activeWindow.getElement('#alert_button');33 assert(alertButton && typeof alertButton === 'object');34 });35 // this is very slow:36 // await test('selecting an element that does not exist throws an exception', async () => {37 // try {38 // await driver.activeWindow.getElement('#does_not_exist');39 // } catch (ex) {40 // assert.equal(ex.code, 'NoSuchElement');41 // return;42 // }43 // assert(false, 'Expected getting a non-existent element to throw an error');44 // });45 await test('selecting an element that does not exist throws an exception', async () => {46 assert(47 null === (await driver.activeWindow.tryGetElement('#does_not_exist')),48 'Expected getting a non-existent element to return null',49 );50 });51 await test("select a single element's id", async () => {52 const alertButton = await driver.activeWindow.getElement('#alert_button');53 const elementID = alertButton.elementID;54 assert(elementID.length > 0);55 });56 await test('select a single element by name', async () => {57 const element = await driver.activeWindow.getElement('q', SelectorTypes.NAME);58 assert(element);59 });60 await test('select a single element by id and check tag name', async () => {61 const inputField = await driver.activeWindow.getElement('inputField', SelectorTypes.ID);62 assert.equal(await inputField.getTagName(), 'input');63 });64 await test('get the computed css value of a single element', async () => {65 const areaToClick = await driver.activeWindow.getElement('#areaToClick');66 assert.equal(await areaToClick.getCssValue('width'), '500px');67 });68 await test('check an element class existence', async () => {69 const inputField = await driver.activeWindow.getElement('#inputField');70 assert(await inputField.hasClass('hasThisClass'));71 assert(await inputField.hasClass('andAnotherClass'));72 assert(!await inputField.hasClass('doesNotHaveClass'));73 });74 await test('compare elements', async () => {75 const inputField = await driver.activeWindow.getElement('#inputField');76 const confirmButton = await driver.activeWindow.getElement('#confirm_button');77 assert(!await inputField.isEqual(confirmButton));78 assert(!await confirmButton.isEqual(inputField));79 const inputFieldByClass = await driver.activeWindow.getElement('hasThisClass', SelectorTypes.CLASS);80 assert(await inputField.isEqual(inputFieldByClass));81 assert(await inputFieldByClass.isEqual(inputField));82 });83 await test('check if an element is enabled', async () => {84 const firstCheckBox = await driver.activeWindow.getElement('#firstCheckBox');85 assert(await firstCheckBox.isEnabled());86 assert(!await firstCheckBox.isDisabled());87 const thirdCheckBox = await driver.activeWindow.getElement('#thirdCheckBox');88 assert(!await thirdCheckBox.isEnabled());89 assert(await thirdCheckBox.isDisabled());90 });91 await test('check if an item is selected', async () => {92 const firstCheckBox = await driver.activeWindow.getElement('#firstCheckBox');93 assert(await firstCheckBox.isSelected());94 const secondCheckBox = await driver.activeWindow.getElement('#secondCheckBox');95 assert(!await secondCheckBox.isSelected());96 });97 await test('submit a form', async () => {98 const formToSubmit = await driver.activeWindow.getElement('#formToSubmit');99 await formToSubmit.submit();100 const url = await driver.activeWindow.getUrl();101 assert.equal(url.substr(-7), '?q=1357');102 });103 await test('click on an element', async () => {104 const areaToClick = await driver.activeWindow.getElement('#areaToClick');105 await areaToClick.mouse.click();106 assert.equal(await areaToClick.getText(), 'clicked left at 450x75');107 });108 await test('click on an element with right button', async () => {109 const areaToClick = await driver.activeWindow.getElement('#areaToClick');110 await areaToClick.mouse.click(MouseButtons.RIGHT);111 assert.equal(await areaToClick.getText(), 'clicked right');112 });113 // N.B. we do not test middle click, because it causes the build to fail on a mac114 await test('click on an element at a specific place', async () => {115 const areaToClick = await driver.activeWindow.getElement('#areaToClick');116 await areaToClick.mouse.clickAt(14, 17);117 assert.equal(await areaToClick.getText(), 'clicked left at 214x67');118 });119 await test('double-click on an element', async () => {120 const areaToClick = await driver.activeWindow.getElement('#areaToClick');121 await areaToClick.mouse.doubleClick();122 assert.equal(await areaToClick.getText(), 'double clicked left at 450x75');123 });124 await test('double-click on an element at a specific place', async () => {125 const areaToClick = await driver.activeWindow.getElement('#areaToClick');126 await areaToClick.mouse.doubleClickAt(14, 17);127 assert.equal(await areaToClick.getText(), 'double clicked left at 214x67');128 });129 await test('click down on an element', async () => {130 const areaToClick = await driver.activeWindow.getElement('#areaToClick');131 await areaToClick.mouse.buttonDownAt(13, 16);132 await areaToClick.mouse.buttonUpAt(13, 16);133 assert.equal(await areaToClick.getText(), 'clicked left at 213x66');134 });135 await test('click up on an element', async () => {136 const areaToClick = await driver.activeWindow.getElement('#areaToClick');137 await areaToClick.mouse.buttonDownAt(88, 32);138 await areaToClick.mouse.buttonUpAt(88, 32);139 assert.equal(await areaToClick.getText(), 'clicked left at 288x82');140 });141 await test('click down and up on an element', async () => {142 const areaToClick = await driver.activeWindow.getElement('#areaToClick');143 await areaToClick.mouse.buttonDown();144 await areaToClick.mouse.buttonUp();145 assert.equal(await areaToClick.getText(), 'clicked left at 450x75');146 });147 await test('get the size of an element', async () => {148 const inputField = await driver.activeWindow.getElement('#inputField');149 const size = await inputField.getSize();150 assert.equal(typeof size, 'object');151 assert(size.hasOwnProperty('width'));152 assert(size.hasOwnProperty('height'));153 });154 await test('get the position of an element', async () => {155 const inputField = await driver.activeWindow.getElement('#inputField');156 const position = await inputField.getPosition();157 assert.equal(typeof position, 'object');158 assert(position.hasOwnProperty('x'));159 assert(position.hasOwnProperty('y'));160 });161 await test('get the frame of an element', async () => {162 const inputField = await driver.activeWindow.getElement('#inputField');163 const frame = await inputField.getFrame();164 assert.equal(typeof frame, 'object');165 assert(frame.hasOwnProperty('x'));166 assert(frame.hasOwnProperty('y'));167 assert(frame.hasOwnProperty('width'));168 assert(frame.hasOwnProperty('height'));169 });170 await test('get the absolute-center of an element', async () => {171 const inputField = await driver.activeWindow.getElement('#inputField');172 const center = await inputField.getAbsoluteCenter();173 assert.equal(typeof center, 'object');174 assert(center.hasOwnProperty('x'));175 assert(center.hasOwnProperty('y'));176 });177 await test('get the relative-center of an element', async () => {178 const inputField = await driver.activeWindow.getElement('#inputField');179 const center = await inputField.getRelativeCenter();180 assert.equal(typeof center, 'object');181 assert(center.hasOwnProperty('x'));182 assert(center.hasOwnProperty('y'));183 });184 await test('select multiple elements', async () => {185 const elements = await driver.activeWindow.getElements('.class-selectable');186 assert.equal(elements.length, 2);187 });188 await test('check if element exist', async () => {189 assert(await driver.activeWindow.hasElement('.class-selectable'));190 assert(!await driver.activeWindow.hasElement('.class2-selectable'));191 });192 await test('get a sub-element from a context', async () => {193 const container = await driver.activeWindow.getElement('#container');194 const subElement = await container.getElement('#sub-element');195 assert.equal(await subElement.getText(), 'Sub-Element');196 const subElement2 = await container.getElement('.someSubElement');197 assert.equal(await subElement2.getText(), 'Some Sub-Element');198 });199 await test('get multiple sub-elements from a context', async () => {200 const container = await driver.activeWindow.getElement('#container');201 const subElements = await container.getElements('div');202 assert(Array.isArray(subElements));203 assert.equal(subElements.length, 2);204 });205 await test('check if sub-elements exist', async () => {206 const container = await driver.activeWindow.getElement('#container');207 assert(await container.hasElement('.someSubElement'));208 assert(!await container.hasElement('.somenNonExistentSubElement'));209 });210 await test('get the active element', async () => {211 const element = await driver.activeWindow.getActiveElement();212 assert(element && typeof element === 'object');213 });214 await test('get the title of the active window', async () => {215 assert.equal(await driver.activeWindow.getTitle(), 'Test Page');216 });217 await test('get the source-code of the active window', async () => {218 const source = await driver.activeWindow.getSource();219 assert(source.includes('<!DOCTYPE html>'));220 });221 await test('click on a link', async () => {222 const linkToClick = await driver.activeWindow.getElement('#linkToClick');223 await linkToClick.mouse.click();224 assert.equal(await driver.activeWindow.getTitle(), 'Linked Page');225 });226 await test('send keys to the active window', async () => {227 await driver.activeWindow.sendKeys('a');228 const typeKeyPress = await driver.activeWindow.getElement('#typeKeyPress');229 assert.equal(await typeKeyPress.getText(), 'KeyPress:97');230 const typeKeyUp = await await driver.activeWindow.getElement('#typeKeyUp');231 assert.equal(await typeKeyUp.getText(), 'KeyUp:65');232 await driver.activeWindow.sendKeys(['a', 'b']);233 assert.equal(await typeKeyPress.getText(), 'KeyPress:98');234 assert.equal(await typeKeyUp.getText(), 'KeyUp:66');235 const typeKeyDown = await driver.activeWindow.getElement('#typeKeyDown');236 assert.equal(await typeKeyDown.getText(), 'KeyDown:66');237 });238 await test('go backward', async () => {239 await driver.activeWindow.goBackward();240 });241 await test('go forward', async () => {242 await driver.activeWindow.goForward();243 await driver.activeWindow.goBackward();244 });245 await test('refresh', async () => {246 await driver.activeWindow.refresh();247 });248 await test('accept an alert', async () => {249 const alertButton = await driver.activeWindow.getElement('#alert_button');250 await alertButton.mouse.click();251 assert.equal(await driver.activeWindow.alert.getText(), 'This is a test alert!');252 await driver.activeWindow.alert.accept();253 assert.equal(await alertButton.getText(), 'alerted');254 });255 await test('accept a confirm', async () => {256 const confirmButton = await driver.activeWindow.getElement('#confirm_button');257 await confirmButton.mouse.click();258 assert.equal(await driver.activeWindow.alert.getText(), 'Test confirmation');259 await driver.activeWindow.alert.accept();260 assert.equal(await confirmButton.getText(), 'confirmed');261 });262 await test('dismiss a confirm', async () => {263 const confirmButton = await driver.activeWindow.getElement('#confirm_button');264 await confirmButton.mouse.click();265 assert.equal(await driver.activeWindow.alert.getText(), 'Test confirmation');266 await driver.activeWindow.alert.dismiss();267 assert.equal(await confirmButton.getText(), 'denied');268 });269 await test('accept a prompt with default value', async () => {270 const promptButton = await driver.activeWindow.getElement('#prompt_button');271 await promptButton.mouse.click();272 assert.equal(await driver.activeWindow.alert.getText(), 'Test Prompt:');273 await driver.activeWindow.alert.accept();274 assert.equal(await promptButton.getText(), 'prompted: default value');275 });276 await test('accept a prompt with custom value', async () => {277 const promptButton = await driver.activeWindow.getElement('#prompt_button');278 await promptButton.mouse.click();279 assert.equal(await driver.activeWindow.alert.getText(), 'Test Prompt:');280 await driver.activeWindow.alert.setText('Works!');281 await driver.activeWindow.alert.accept();282 assert.equal(await promptButton.getText(), 'prompted: Works!');283 });284 await test('dismiss a prompt', async () => {285 const promptButton = await driver.activeWindow.getElement('#prompt_button');286 await promptButton.mouse.click();287 assert.equal(await driver.activeWindow.alert.getText(), 'Test Prompt:');288 await driver.activeWindow.alert.dismiss();289 assert.equal(await promptButton.getText(), 'prompted: null');290 });291 await test('execute javascript code as string', async () => {292 await driver.activeWindow.execute("alert('test-32');");293 assert.equal(await driver.activeWindow.alert.getText(), 'test-32');294 await driver.activeWindow.alert.accept();295 });296 // This test does not play well with snapshots:297 // await test('execute javascript code as a function', async () => {298 // await driver.activeWindow.execute(function() {299 // alert('test-33');300 // });301 // assert.equal(await driver.activeWindow.alert.getText(), 'test-33');302 // await driver.activeWindow.alert.accept();303 // });304 await test('execute javascript code as a function with parameters', async () => {305 const alertButtonText = await driver.activeWindow.execute(306 'return document.getElementById(arguments[0]).textContent;',307 ['alert_button'],308 );309 assert.equal(alertButtonText, 'alerted');310 });311 await test('execute asynchronous javascript code', async () => {312 await driver.activeWindow.asyncExecute("alert('test-35');");313 assert.equal(await driver.activeWindow.alert.getText(), 'test-35');314 await driver.activeWindow.alert.accept();315 });316 await test('take a screenshot', async () => {317 const buffer = await driver.activeWindow.takeScreenshot();318 assert(buffer instanceof Buffer);319 });320 await test('set a value in cookie-storage', async () => {321 const cookie1 = {322 name: 'testKey',323 value: '2468',324 };325 const cookie2 = {326 name: 'testKeySecond',327 value: 'hello',328 };329 await driver.cookieStorage.setCookie(cookie1);330 await driver.cookieStorage.setCookie(cookie2);331 });332 await test('get a value in cookie-storage', async () => {333 const cookie = await driver.cookieStorage.getCookie('testKey');334 if (!cookie) {335 throw new Error('Cookie should not be undefined');336 }337 assert.equal(cookie.name, 'testKey');338 assert.equal(cookie.value, '2468');339 });340 await test('get the size of cookie-storage', async () => {341 const size = await driver.cookieStorage.getSize();342 assert(typeof size === 'number');343 });344 await test('get all keys in cookie-storage', async () => {345 const keys = await driver.cookieStorage.getKeys();346 assert(keys.includes('testKey'));347 assert(keys.includes('testKeySecond'));348 });349 await test('remove a key from cookie-storage', async () => {350 await driver.cookieStorage.removeCookie('testKey');351 const keys = await driver.cookieStorage.getKeys();352 assert(!keys.includes('testKey'));353 assert(keys.includes('testKeySecond'));354 });355 await test('get all cookies in cookie-storage', async () => {356 const cookies = await driver.cookieStorage.getCookies();357 assert(Array.isArray(cookies));358 });359 await test('clear the cookie-storage', async () => {360 await driver.cookieStorage.clear();361 assert.equal(await driver.cookieStorage.getSize(), 0);362 });363 await test('set a value in local-storage', async () => {364 await driver.localStorage.setItem('testKey', '2468');365 await driver.localStorage.setItem('testKeySecond', 'hello');366 });367 await test('get a value in local-storage', async () => {368 assert.equal(await driver.localStorage.getItem('testKey'), '2468');369 });370 await test('get the size of local-storage', async () => {371 assert.equal(await driver.localStorage.getSize(), 2);372 });373 await test('get all keys in local-storage', async () => {374 assert.deepEqual(await driver.localStorage.getKeys(), ['testKey', 'testKeySecond']);375 });376 await test('remove a key from local-storage', async () => {377 await driver.localStorage.removeItem('testKey');378 assert.equal(await driver.localStorage.getSize(), 1);379 assert.deepEqual(await driver.localStorage.getKeys(), ['testKeySecond']);380 });381 await test('clear the local-storage', async () => {382 await driver.localStorage.clear();383 assert.equal(await driver.localStorage.getSize(), 0);384 });385 await test('set a value in session-storage', async () => {386 await driver.sessionStorage.setItem('testKey', '2468');387 await driver.sessionStorage.setItem('testKeySecond', 'hello');388 });389 await test('get a value in session-storage', async () => {390 assert.equal(await driver.sessionStorage.getItem('testKey'), '2468');391 });392 await test('get the size of session-storage', async () => {393 assert.equal(await driver.sessionStorage.getSize(), 2);394 });395 await test('get all keys in session-storage', async () => {396 assert.deepEqual(await driver.sessionStorage.getKeys(), ['testKey', 'testKeySecond']);397 });398 await test('remove a key from session-storage', async () => {399 await driver.sessionStorage.removeItem('testKey');400 assert.equal(await driver.sessionStorage.getSize(), 1);401 assert.deepEqual(await driver.sessionStorage.getKeys(), ['testKeySecond']);402 });403 await test('clear the session-storage', async () => {404 await driver.sessionStorage.clear();405 assert.equal(await driver.sessionStorage.getSize(), 0);406 });407 await test('get the text of an element', async () => {408 const element = await driver.activeWindow.getElement('q', SelectorTypes.NAME);409 assert.equal(await element.getAttribute('value'), '1357');410 });411 await test('clear the text of an input element', async () => {412 const element = await driver.activeWindow.getElement('[name="q"]');413 await element.clear();414 assert.equal(await element.getAttribute('value'), '');415 });416 await test('write text into an input element', async () => {417 const element = await driver.activeWindow.getElement('q', SelectorTypes.NAME);418 await element.sendKeys('test-45');419 assert.equal(await element.getAttribute('value'), 'test-45');420 });421 await test('get a server status', async () => {422 const status = await getStatus(driver.remote, driver.options);423 // Not required, but still execute and see if fails424 status.getBuildVersion();425 status.getBuildRevision();426 status.getBuildTime();427 // Sauce labs doesn't support these so we return undefined428 status.getOSVersion();429 status.getOSArchitecture();430 status.getOSName();431 });432 // TODO: this feature is not supported by sauce labs:433 // test("get a session list", async () => {434 // const sessions = await getSessions(driver.remote, driver.options);435 // console.log(sessions);436 // });437 await test('get capabilities information', async () => {438 const session = await driver.session;439 console.dir(session.capabilities);440 });441 await test('get an element', async () => {442 const element = await driver.activeWindow.getElement('h1');443 });444 await test('test whether an element is displayed', async () => {445 const element = await driver.activeWindow.getElement('h1');446 assert(await element.isDisplayed());447 const hiddenElement = await driver.activeWindow.getElement('#hidden');448 assert(!await hiddenElement.isDisplayed());449 });450 await test('get an attribute of an element', async () => {451 const element = await driver.activeWindow.getElement('#has-attribute');452 assert.equal(await element.getAttribute('data-attribute'), 'value');453 });454 await test('type text into an element', async () => {455 const element = await driver.activeWindow.getElement('[name="q"]');456 await element.clear();457 await element.sendKeys('hello');458 await element.sendKeys([' ', 'world']);459 assert.equal(await element.getAttribute('value'), 'hello world');460 await element.clear();461 assert.equal(await element.getAttribute('value'), '');462 });463 await test('get the text content of an element', async () => {464 const element = await driver.activeWindow.getElement('#has-text');465 assert.equal(await element.getText(), 'test content');466 });467 await test('click on a button', async () => {468 const button = await driver.activeWindow.getElement('#clickable');469 await button.mouse.click();470 assert.equal(await button.getText(), 'clicked');471 });472 await test('get the position of the active window', async () => {473 const position = await driver.activeWindow.getPosition();474 assert.equal(typeof position, 'object');475 assert.equal(typeof position.x, 'number');476 assert.equal(typeof position.y, 'number');477 });478 await test('get the size of the active window', async () => {479 const size = await driver.activeWindow.getSize();480 assert.equal(typeof size, 'object');481 assert.equal(typeof size.width, 'number');482 assert.equal(typeof size.height, 'number');483 });484 await test('resize the active window', async () => {485 await driver.activeWindow.resize(500, 300);486 assert.deepEqual(await driver.activeWindow.getSize(), {width: 500, height: 300});487 });488 await test('position the active window', async () => {489 await driver.activeWindow.position(160, 163);490 assert.deepEqual(await driver.activeWindow.getPosition(), {x: 160, y: 163});491 });492 await test('maximize the active window', async () => {493 await driver.activeWindow.maximize();494 });495 await test('close the active window', async () => {496 await driver.activeWindow.close();497 });498}499// TODO: sauce job info500// TODO: test touch interface...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import {typekit, validationkit} from 'basekits'2import EventEmitterObject from 'event-emitter-object'3import LocalStorageDriver from './drivers/localStorage'4import MemoryDriver from './drivers/memory'5function LocalStoragePro() {6 EventEmitterObject.call(this, {})7 this.window = undefined8 this.setWindow(typeof window == 'undefined' ? undefined : window)9 this.drivers = {}10 this.driver = null11 this.addDriver('memory', MemoryDriver)12 this.addDriver('localStorage', LocalStorageDriver)13}14LocalStoragePro.prototype = Object.create(EventEmitterObject.prototype)15LocalStoragePro.prototype.constructor = LocalStoragePro16LocalStoragePro.prototype.length = 017LocalStoragePro.prototype.setWindow = function setWindow(w) {18 this.window = w19}20LocalStoragePro.prototype.addDriver = function addDriver(name, Driver) {21 const instance = new Driver({window: this.window})22 if (instance.test() === true) {23 this.drivers[name] = instance24 this.driver = this.drivers[name]25 }26}27LocalStoragePro.prototype.setItem = function setItem(key, value, driver = null) {28 if (!this.isKeyValid(key)) {29 this.emit('error', new Error('INVALID_KEY'))30 return undefined31 }32 const activeDriver = this.getDriver(driver)33 if (activeDriver) {34 activeDriver.set( this.formatKey(key), value, this )35 if (typekit.isError(activeDriver.error)) {36 this.emit('error', new Error('SET_ERROR'), activeDriver.error)37 activeDriver.clearError()38 return undefined39 }40 this.getLength()41 return true42 }43 else return undefined44}45LocalStoragePro.prototype.getItem = function getItem(key, driver = null) {46 if (!this.isKeyValid(key)) {47 this.emit('error', new Error('INVALID_KEY'))48 return undefined49 }50 const activeDriver = this.getDriver(driver)51 if (activeDriver) {52 const v = activeDriver.get( this.formatKey(key), this )53 this.getLength()54 return v55 }56 else return undefined57}58LocalStoragePro.prototype.removeItem = function removeItem(key, driver = null) {59 if (!this.isKeyValid(key)) {60 this.emit('error', new Error('INVALID_KEY'))61 return undefined62 }63 const activeDriver = this.getDriver(driver)64 if (activeDriver) {65 activeDriver.remove( this.formatKey(key) )66 this.getLength()67 }68 else return undefined69 return true70}71LocalStoragePro.prototype.clear = function clear(driver = null) {72 const activeDriver = this.getDriver(driver)73 if (activeDriver) {74 activeDriver.clear()75 this.getLength()76 }77 return true78}79LocalStoragePro.prototype.key = function key(index = 0, driver = null) {80 const activeDriver = this.getDriver(driver)81 return activeDriver ? activeDriver.getKey(index) : null82}83LocalStoragePro.prototype.getLength = function getLength(driver = null) {84 const activeDriver = this.getDriver(driver)85 this.length = activeDriver ? activeDriver.length() : 086 return this.length87}88LocalStoragePro.prototype.json = function json(driver = null) {89 const activeDriver = this.getDriver(driver)90 return activeDriver ? activeDriver.json(this) : 091}92LocalStoragePro.prototype.isKeyValid = function isKeyValid(k) {93 return (typekit.isString(k) && validationkit.isNotEmpty(k)) || typekit.isNumber(k)94}95LocalStoragePro.prototype.formatKey = function formatKey(k) {96 if (typekit.isNumber(k)) return k.toString()97 else return k98}99LocalStoragePro.prototype.availableDrivers = function availableDrivers() {100 return Object.keys(this.drivers)101}102LocalStoragePro.prototype.getDriver = function getDriver(driver = null) {103 if (validationkit.isNotEmpty(driver)) {104 if (this.availableDrivers().indexOf(driver) === -1) {105 this.emit('error', new Error('DRIVER_NOT_FOUND'))106 return undefined107 }108 return this.drivers[driver]109 }110 return this.driver111}...

Full Screen

Full Screen

helpers.js

Source:helpers.js Github

copy

Full Screen

1exports.retrieveDriverCoordinates = (driver) => {2 return {3 x: driver.activeLegID.startStop.x + (driver.activeLegID.endStop.x - driver.activeLegID.startStop.x) * driver.legProgress / 100,4 y: driver.activeLegID.startStop.y + (driver.activeLegID.endStop.y - driver.activeLegID.startStop.y) * driver.legProgress / 1005 }6}7exports.checkForCompletion = (leg, driver) => {8 if (driver && driver.activeLegID && driver.activeLegID.legID > leg.legID)9 return true;10 else11 return false;12}13exports.getArrayOfLegsNeedingCompletion = (legs, closestStopToDriver) => {14 // first sort legs15 const sortedLegs = legs.sort((legA, legB) => {16 return legA.legID >= legB.legID ? 1 : -1;17 });18 let needCompletion = false;19 let result = [];20 sortedLegs.forEach((leg) => {21 if (leg.startStop.name === closestStopToDriver.name)22 needCompletion = true;23 if (needCompletion)24 result.push(leg);25 });26 return result;27}28exports.calculateTimeLeft = (driver, legs) => {29 let time = 0;30 legs.forEach(leg => {31 if (!this.checkForCompletion(leg, driver)) {32 let distance = calculateDistance(leg.startStop.x, leg.endStop.x, leg.startStop.y, leg.endStop.y);33 if (driver.activeLegID.legID === leg.legID)34 distance = distance * (100 - driver.legProgress) / 100;35 time += distance / leg.speedLimit;36 }37 });38 return parseFloat(time).toFixed(2);39}40exports.formatTime = (time) => {41 const hours = Math.floor(time);42 const minutes = (time % 1) * 60;43 const seconds = Math.round((minutes % 1) * 60);44 return `${hours} hours, ${Math.floor(minutes)} minutes & ${seconds} seconds`;45}46exports.findTheClosestStop = (stops, driverLocation) => {47 let result = { name: "", x: null, y: null };48 let shortestDistance = null;49 stops.forEach((stop) => {50 const distanceToStop = calculateDistance(driverLocation.x, driverLocation.y, stop.x, stop.y);51 if (shortestDistance === null || shortestDistance > distanceToStop) {52 result = { name: stop.name, x: stop.x, y: stop.y };53 shortestDistance = distanceToStop;54 }55 })56 return result;57}58function calculateDistance(startStopX, startStopY, endStopX, endStopY) {59 return Math.sqrt(Math.abs((startStopX - endStopX) * (startStopX - endStopX)) + Math.abs((startStopY - endStopY) * (startStopY - endStopY)));...

Full Screen

Full Screen

getAllDriver.js

Source:getAllDriver.js Github

copy

Full Screen

1const { toKiloMeter } = require('../helpers//toKm')2const { consumer } = require('../libs/kafka')3exports.getAllDrivers = function (io, socket, db) {4 socket.on(`client:send`, async (userId) => {5 let getOrderByMitra = await db('order')6 .select('*', db.raw('to_json(location) as location'), db.raw('to_json(location) as destination'))7 .where('customer_id', userId)8 .andWhere('status', 'pesanan menunggu konfirmasi')9 .andWhere('order_date', '>=', `${new Date().toLocaleDateString()}T00:00:00.00Z`)10 .first()11 let getAllDriverActive = []12 if (getOrderByMitra) {13 // get data from datase if user reloading data14 if (!getAllDriverActive.length) {15 getAllDriverActive = await db('point_location')16 .select('id', 'driver_id', 'active', 'latitude', 'longitude')17 .where('active', true)18 const newGetAllDriverActive = getAllDriverActive19 .map((val) => {20 const latitude = parseFloat(getOrderByMitra.location.latitude)21 const longitude = parseFloat(getOrderByMitra.location.longitude)22 return toKiloMeter(latitude, longitude, val.latitude, val.longitude) <= 10 ? val : false23 })24 .filter((val) => typeof val != 'boolean')25 io.emit(`server:send:${userId}`, JSON.stringify(newGetAllDriverActive))26 }27 // get data from kafka if user not reloading data28 await consumer('pointLocation', async ({ topic, partition, message }) => {29 const streamingPayload = message.value.toString()30 getAllDriverActive = JSON.parse(streamingPayload)31 const newGetAllDriverActive = getAllDriverActive32 .map((val) => {33 const latitude = parseFloat(getOrderByMitra.location.latitude)34 const longitude = parseFloat(getOrderByMitra.location.longitude)35 return toKiloMeter(latitude, longitude, val.latitude, val.longitude) <= 10 ? val : false36 })37 .filter((val) => typeof val != 'boolean')38 io.emit(`server:send:${userId}`, JSON.stringify(newGetAllDriverActive))39 })40 }41 })...

Full Screen

Full Screen

HomePage.js

Source:HomePage.js Github

copy

Full Screen

1import React, { Component } from "react";2import DriverHeader from "./DriverHeader";3import DriverInactive from "./DriverInactive";4import DriverActiveNoRide from "./DriverActiveNoRide";5import DriverActiveOnRide from "./DriverActiveOnRide";6export default class HomePage extends Component {7 constructor(props) {8 super(props);9 this.state = {};10 }11 render() {12 let relevantView;13 const activeRides = this.props.user.driverData.rides.filter(14 ride =>15 ride.ride_status !== "waiting_on_driver" &&16 ride.ride_status !== "complete"17 );18 const driverActive = this.props.user.driverData.active;19 if (!driverActive && !activeRides.length) {20 relevantView = (21 <DriverInactive22 user={this.props.user}23 usrUpdate={this.props.usrUpdate}24 refreshUserData={this.props.refreshUserData}25 usrLoading={this.props.usrLoading}26 />27 );28 } else if (activeRides.length > 0) {29 relevantView = (30 <DriverActiveOnRide31 user={this.props.user}32 currentRide={activeRides[0]}33 refreshUserData={this.props.refreshUserData}34 usrLoading={this.props.usrLoading}35 />36 );37 } else if (driverActive) {38 relevantView = (39 <DriverActiveNoRide40 user={this.props.user}41 usrUpdate={this.props.usrUpdate}42 refreshUserData={this.props.refreshUserData}43 usrLoading={this.props.usrLoading}44 />45 );46 }47 return (48 <>49 <DriverHeader user={this.props.user} />50 {relevantView}51 </>52 );53 }...

Full Screen

Full Screen

DriverActiveNoRide.js

Source:DriverActiveNoRide.js Github

copy

Full Screen

1import React, { Component } from "react";2import Grid from "@material-ui/core/Grid";3import DriverHUD from "./DriverHUD";4import DriverActiveRides from "./DriverActiveRides";5export default class DriverActiveNoRide extends Component {6 constructor(props) {7 super(props);8 this.state = {};9 }10 render() {11 return (12 <div style={{ padding: "50px" }}>13 <Grid14 container15 direction="row"16 justify="space-around"17 alignItems="flex-start"18 spacing={24}19 >20 <Grid item xs={12} sm={6}>21 <DriverHUD22 user={this.props.user}23 usrUpdate={this.props.usrUpdate}24 usrLoading={this.props.usrLoading}25 />26 </Grid>27 <Grid item xs={12} sm={6}>28 <DriverActiveRides29 user={this.props.user}30 usrUpdate={this.props.usrUpdate}31 refreshUserData={this.props.refreshUserData}32 />33 </Grid>34 </Grid>35 </div>36 );37 }...

Full Screen

Full Screen

5-DIP.js

Source:5-DIP.js Github

copy

Full Screen

...18 car.run();19 }20}21let driver = new Driver();22driver.active(new BWM());...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5chai.should();6const { serverConfig } = require('./config');7const driver = wd.promiseChainRemote(serverConfig);8describe('Active Method Test', () => {9 before(async () => {10 await driver.init(serverConfig.capabilities);11 });12 after(async () => {13 await driver.quit();14 });15 it('should return active app', async () => {16 const activeApp = await driver.active();17 activeApp.should.exist;18 });19});20const serverConfig = {21 capabilities: {22 }23};24module.exports = {25};26{27 "scripts": {28 },29 "dependencies": {30 }31}32const serverConfig = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2driver.init({3})4 .then(function() {5 return driver.active();6 })7 .then(function(active) {8 console.log(active);9 })10 .fin(function() {11 return driver.quit();12 })13 .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var driver = wd.promiseChainRemote({3});4driver.init({5}).then(function() {6 return driver.active();7}).then(function() {8 console.log('App is active');9}).fin(function() {10 return driver.quit();11}).done();12var wd = require('wd');13var driver = wd.promiseChainRemote({14});15driver.init({16}).then(function() {17 return driver.active();18}).then(function() {19 console.log('App is active');20}).fin(function() {21 return driver.quit();22}).done();23var wd = require('wd');24var driver = wd.promiseChainRemote({25});26driver.init({27}).then(function() {28 return driver.active();29}).then(function() {30 console.log('App is active');31}).fin(function() {32 return driver.quit();33}).done();34var wd = require('wd');35var driver = wd.promiseChainRemote({36});37driver.init({38}).then(function() {39 return driver.active();40}).then(function() {

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .withCapabilities({4 })5 .build();6driver.active().then(function(){7 console.log('active app');8 driver.quit();9});10driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const desiredCaps = {3};4driver.init(desiredCaps)5 .then(() => {6 return driver.active()7 })8 .then((activeElement) => {9 console.log(activeElement);10 })11 .catch((err) => {12 console.log(err);13 });14const wd = require('wd');15const desiredCaps = {16};17driver.init(desiredCaps)18 .then(() => {19 return driver.active()20 })21 .then((activeElement) => {22 return activeElement.getAttribute('name')23 })24 .then((name) => {25 console.log(name);26 })27 .catch((err) => {28 console.log(err);29 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const assert = require('assert');3const opts = {4 capabilities: {5 }6};7async function main() {8 const client = await wdio.remote(opts);9 const active = await client.active();10 console.log(active);11 assert(active.ELEMENT);12 client.deleteSession();13}14main();15const wdio = require('webdriverio');16const assert = require('assert');17const opts = {18 capabilities: {19 }20};21async function main() {22 const client = await wdio.remote(opts);23 const active = await client.active();24 console.log(active);25 assert(active.ELEMENT);26 client.deleteSession();27}28main();29const wdio = require('webdriverio');30const assert = require('assert');31const opts = {

Full Screen

Using AI Code Generation

copy

Full Screen

1(async function example() {2 var wd = require('wd');3 var chai = require('chai');4 var chaiAsPromised = require('chai-as-promised');5 chai.use(chaiAsPromised);6 var assert = chai.assert;7 var should = chai.should();8 var expect = chai.expect;9 var desiredCaps = {10 };11 await driver.init(desiredCaps);12 await driver.sleep(10000);13 await driver.active();14 await driver.quit();15})();16(async function example() {17 var wd = require('wd');18 var chai = require('chai');19 var chaiAsPromised = require('chai-as-promised');20 chai.use(chaiAsPromised);21 var assert = chai.assert;22 var should = chai.should();23 var expect = chai.expect;24 var desiredCaps = {

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful